I have a problem with Java and XML. I have a registration form that saves the new user in a file users.xml and I want to check, before save the current user, if there exists another user with the same username.
This is my XML:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<user id="1">
<username>John</username>
<password>mypassword</password>
</user>
And this is my code:
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;
}
}
But everytime I use:
if(isUserExisting.checkIfExists(username)) {
System.out.println("This username exists");
}
I receive the following error:
[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.
What's the problem? Thanks in advance :)