-1
我对Java和XML有问题。 我有一个注册表单,它将新用户保存在文件users.xml中,我希望在保存当前用户之前检查是否存在具有相同用户名的其他用户。Java XML检查节点是否存在
这是我的XML:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<user id="1">
<username>John</username>
<password>mypassword</password>
</user>
这是我的代码:
public class isUserExisting {
public static boolean checkIfExists(String username) {
try {
File inputFile = new File("src/users.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("user");
System.out.println("----------------------------");
for (int temp = nList.getLength() - 1; temp >= 0 ; temp--) {
Node nNode = nList.item(temp);
System.out.println();
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String tempUser = eElement.getElementsByTagName("username").item(0).getTextContent();
if(tempUser == username) {
return true;
}
else {
return false;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
但每次我用:
if(isUserExisting.checkIfExists(username)) {
System.out.println("This username exists");
}
我收到以下错误:
[Fatal Error] users.xml:6:2: The markup of the document that follow the element must have a correct format.
org.xml.sax.SAXParseException; systemId: file:/eclipse/workspace/Folder/src/users.xml; lineNumber: 6; columnNumber: 2; The markup of the document that follow the element must have a correct format.
什么问题?在此先感谢:)
只能有一个根元素在XML中,所以如果你打算有多个用户,你需要一个外部元素。 – Andreas
与错误无关,但请参阅[如何比较Java中的字符串?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Andreas
为什么不只是使用单个XPath表达式用于检查? –