-1

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 :)

Simone C.
  • 369
  • 4
  • 14
  • 1
    There can be only one root element in XML, so if you intend to have more than one user, you need an outer element. – Andreas May 02 '16 at 21:17
  • Unrelated to error, but see [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Andreas May 02 '16 at 21:18
  • why not just use a single XPath expression for that checking? – vtd-xml-author May 02 '16 at 21:21

1 Answers1

0

Runs ok for me. I don't get a Fatal Error

To make this work correctly you need to compare Strings properly with the equals() method: Replace

if(tempUser == username)

with

if (tempUser.equals(username))
Mad Matts
  • 1,118
  • 10
  • 14