我遇到了Java和XML的问题。 我有一个注册表单,用于将新用户保存在文件users.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.
问题是什么?在此先感谢:)
答案 0 :(得分:0)
对我来说运行正常。我没有得到Fatal Error
要使其正常工作,您需要使用equals()
方法正确比较字符串:
取代
if(tempUser == username)
带
if (tempUser.equals(username))