英文:
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
<!--I made some modifications in the password field-->
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE Users>
<Users>
<User id = "0001">
<firstname>sinead</firstname>
<lastname>o'connor</lastname>
<email>sinead@oconnor.ie</email>
<username>sinead</username>
<password>oconnor</password>
</User>
<User id= "0002">
<firstname>John</firstname>
<lastname>Don</lastname>
<email>john@don.ie</email>
<username>john</username>
<password>pass</password>
</User>
</Users>
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();
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
}
getUser() method
//I just split between readFile() and getUser() for better readability.
//Just changed "Users" to "User".
void getUser(){
NodeList nodeList = document.getElementsByTagName("User");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
//I also modified this bit.
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())){
System.out.println("\nUsername "+ "\""+ users.getUsername()+ "\"" +
" was not found in our registry." + "\nPlease try again");
//users.login() is just a simple username/password form in another class.
users.login();
}
else 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()));
}
}
}
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.
> 1
Log In.
Please, enter your username:
> john
Please, enter your password:
> pass
Username "john" 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中,username
和 password
标签具有相同的值,你可能需要更改它们以验证输出。
英文:
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("User");
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("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());
}
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("Users");
You probably want to populate the nodelist with
NodeList nodeList = document.getElementsByTagName("User");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论