如何使用Java读取XML文件的所有子元素?

huangapple go评论64阅读模式
英文:

How can I read all child elements of a XML file using Java?

问题

// readFile() method
void readFile(){
    String pathXML = "src/user_system/my_library/xml/users.xml";
    File usersXML = new File(pathXML);

    try {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(usersXML);
        document.getDocumentElement().normalize();
        getUser(document); // Call getUser() with the parsed document

    } catch (ParserConfigurationException | SAXException | IOException e) {
        e.printStackTrace();
    }
}

// getUser() method
void getUser(Document document) {
    NodeList nodeList = document.getElementsByTagName("User");

    for (int i = 0; i < nodeList.getLength(); i++) {
        Element xmlElement = (Element) nodeList.item(i);

        String usernameElement = xmlElement.getElementsByTagName("username").item(0)
                .getTextContent();
        String passwordElement = xmlElement.getElementsByTagName("password").item(0)
                .getTextContent();

        if (!usernameElement.equals(users.getUsername())) {
            continue; // Skip this iteration if the username doesn't match
        }

        if (!passwordElement.equals(users.getPassword())) {
            System.out.println("\nWrong password. Please try again.");
            users.login();
        } else {
            System.out.println("Welcome " +
                    WordUtils.capitalize(xmlElement.getElementsByTagName("firstname").item(0)
                            .getTextContent()) +
                    " " +
                    WordUtils.capitalize(xmlElement.getElementsByTagName("lastname").item(0).getTextContent()));
        }
    }
}

Output should now be:

Please, choose one of the options below:
1) Press 1 to Log In.
2) Press 2 to Create an Account.
3) Press 3 to Log Off.
>  1
Log In.
Please, enter your username:
>  john
Please, enter your password:
>  pass
Welcome John Don

This updated code should correctly iterate through all user elements in the XML file and check for matching usernames and passwords.

英文:

The goal: read through the entire XML file and return only specific values, in this case, a "username" and "password", so I validate a user login.

The problem: when the program reads the "users.xml" file, it returns all attributes and values from the "user id=0001", but other child elements like "user id=0002" it won't return. Like there's nothing else in the file but the first element.

What I tried: printing all info from the file using a for loop to read line by line and it works just fine, but when it comes to getting one particular value, it can only see the first one.

I'd like to know how can I make it so that "getUser()" returns any "username" and "password" in the file?

Here's what I have so far:

users.xml

&lt;!--I made some modifications in the password field--&gt;
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;no&quot;?&gt;
&lt;!DOCTYPE Users&gt;
&lt;Users&gt;
&lt;User id = &quot;0001&quot;&gt;
&lt;firstname&gt;sinead&lt;/firstname&gt;
&lt;lastname&gt;o&#39;connor&lt;/lastname&gt;
&lt;email&gt;sinead@oconnor.ie&lt;/email&gt;
&lt;username&gt;sinead&lt;/username&gt;
&lt;password&gt;oconnor&lt;/password&gt;
&lt;/User&gt;
&lt;User id= &quot;0002&quot;&gt;
&lt;firstname&gt;John&lt;/firstname&gt;
&lt;lastname&gt;Don&lt;/lastname&gt;
&lt;email&gt;john@don.ie&lt;/email&gt;
&lt;username&gt;john&lt;/username&gt;
&lt;password&gt;pass&lt;/password&gt;
&lt;/User&gt;
&lt;/Users&gt;

readFile() method

    void readFile(){
String pathXML = &quot;src/user_system/my_library/xml/users.xml&quot;;
File usersXML = new File(pathXML);
try {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(usersXML);
document.getDocumentElement().normalize();
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
}

getUser() method

    //I just split between readFile() and getUser() for better readability.
//Just changed &quot;Users&quot; to &quot;User&quot;.
void getUser(){
NodeList nodeList = document.getElementsByTagName(&quot;User&quot;);
for (int i =  0; i &lt; nodeList.getLength(); i++) {
Node node = nodeList.item(i);
//I also modified this bit.
Element xmlElement = (Element)nodeList.item(i);
String usernameElement = xmlElement.getElementsByTagName(&quot;username&quot;).item(0)
.getTextContent();
String passwordElement = xmlElement.getElementsByTagName(&quot;password&quot;).item(0)
.getTextContent();
if (!usernameElement.equals(users.getUsername())){
System.out.println(&quot;\nUsername &quot;+ &quot;\&quot;&quot;+ users.getUsername()+ &quot;\&quot;&quot; + 
&quot; was not found in our registry.&quot; + &quot;\nPlease try again&quot;);
//users.login() is just a simple username/password form in another class.
users.login();
}
else if(!passwordElement.equals(users.getPassword())){
System.out.println(&quot;\nWrong password. Please try again.&quot;);
users.login();
}else {
System.out.println(&quot;Welcome &quot; + WordUtils.capitalize(xmlElement.getElementsByTagName(&quot;firstname&quot;).item(0)
.getTextContent())+ &quot; &quot; +WordUtils.capitalize(xmlElement.getElementsByTagName(&quot;lastname&quot;).item(0).getTextContent()));
}
}
}

I updated the code, but I still can't get other users, only the first one.
I get the following output:

Please, choose one of the options below:
1) Press 1 to Log In.
2) Press 2 to Create an Account.
3) Press 3 to Log Off.
&gt;  1
Log In.
Please, enter your username: 
&gt;  john
Please, enter your password: 
&gt;  pass
Username &quot;john&quot; was not found in our registry.

Any help is appreciated.

答案1

得分: 1

你可以根据标签名选择所有节点,这里你使用了 Users 作为基础节点,但你也可以通过调用以下方式查询 User 标签,

NodeList nodeList = document.getElementsByTagName("User");

使用上述代码从xml文档的根开始,你只会得到 User 节点。一旦你获得了所有的 User 节点,你可以逐个迭代它们,并查询位于每个 User 节点内部的节点,如下所示:

NodeList nodeList = document.getElementsByTagName("User");
for (int i = 0; i < nodeList.getLength(); i++) {
    Element xmlElement = (Element) nodeList.item(i);
    System.out.println(xmlElement.getElementsByTagName("username").item(0).getTextContent());
    System.out.println(xmlElement.getElementsByTagName("password").item(0).getTextContent());
}

请注意,在你的示例xml中,usernamepassword 标签具有相同的值,你可能需要更改它们以验证输出。

英文:

You can pick up all the nodes based on their tag name, here you have used Users as your base node but you can also query User tag by calling,

NodeList nodeList = document.getElementsByTagName(&quot;User&quot;);

Using code above from root of the xml document you have only User nodes, once you have all the User nodes you can iterate it one by one and query nodes which are inside of User node as shown below.

NodeList nodeList = document.getElementsByTagName(&quot;User&quot;);
for(int i=0;i&lt;nodeList.getLength();i++) {
Element xmlElement = (Element)nodeList.item(i);
System.out.println(xmlElement.getElementsByTagName(&quot;username&quot;).item(0).getTextContent());
System.out.println(xmlElement.getElementsByTagName(&quot;password&quot;).item(0).getTextContent());
}

Note that in your sample xml username and password tag has same values which you might want to change to validate the output.

答案2

得分: 0

一些输出将会很有帮助。
我猜想当您创建 nodelist 时,您正在创建一个长度为 1 的列表,因为 "User" 将会获取带有标签 "Users" 的单个元素。

NodeList nodeList = document.getElementsByTagName("Users");

您可能想要用以下内容填充 nodelist

NodeList nodeList = document.getElementsByTagName("User");

英文:

Some outputs would be helpful.
My guess is that when you create nodelist, you're creating a list of length 1, since "User" will grab the single element with the tag "Users".

NodeList nodeList = document.getElementsByTagName(&quot;Users&quot;);

You probably want to populate the nodelist with

NodeList nodeList = document.getElementsByTagName(&quot;User&quot;);

huangapple
  • 本文由 发表于 2020年10月23日 01:58:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/64487976.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定