I am trying to read a some data that is stored in an xml file and then print it to the screen for the user. But my program isn't working correctly.

Here is my XML document:

<UserAccounts>
    <Account AccountNumber="1234567890">
        <Password>12345</Password>
        <Balance>1024.64</Balance>
    </Account>
</UserAccounts>

And here is my code:

File fXmlFile = new File("Accounts.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);

doc.getDocumentElement().normalize();

NodeList nList = doc.getElementsByTagName("UserAccounts");

for(int temp = 0; temp < nList.getLength(); temp++) {
    Node nNode = nList.item(temp);

     if(nNode.getNodeType() == Node.ELEMENT_NODE) {
         Element element = (Element)nNode;

         String accountNumber = element.getAttribute("AccountNumber");
         String spassword = element.getElementsByTagName("Password").item(0).getTextContent();
         System.out.println("[" + accountNumber + "]\t["+spassword+"]");
     }
}

The variable "accountNumber" does net have a value. Meaning that "accountNumber = element.getAttribute("AccountNumber");" is not working properly.

How do I fix it?

Is that XML correct?
shouldn't

<Account AccountNumber="1234567890">

be

<Account>
   <AccountNumber="1234567890">

given how you are parsing it?

Yes my XML is correct, I have implemented another parser that fixed the problem

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.