Home » Java » Read XML file with more than one value in one tag Using Java

Read XML file with more than one value in one tag Using Java

Posted by: admin July 12, 2018 Leave a comment

Questions:

I have my XML file like this

<Customers>
  <Customer Name="Test_91" Code="91" Purpose="Supplier" />
  <Customer Name="Test_92" Code="92" Purpose="Receiver" />
</Customers>

I need to read this file with java and I use code like this:

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public class XMLReaderDOM {

    public static void main(String argv[]) {
        try {
            File fXmlFile = new File("Customers.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();

            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
            NodeList nList = doc.getElementsByTagName("Customers");

            for (int temp = 0; temp < nList.getLength(); temp++) {
                Node nNode = nList.item(temp);
                System.out.println("\nCurrent Element :" + nNode);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                    Element eElement = (Element) nNode;


                    System.out.println("Customer id : "
                            + ((Element) eElement.getElementsByTagName("Customer").item(0)).getAttribute("Name"));
                    System.out.println("IataCode : "
                            + ((Element) eElement.getElementsByTagName("Customer").item(0)).getAttribute("Code"));
                    System.out.println("IcaoCode : "
                            + ((Element) eElement.getElementsByTagName("Customer").item(0)).getAttribute("Purpose"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

But I am not getting the values of second record. which are details of customer “Test_92”.

Can someone help me to read the values of N number of customers?

Thanks in Advance!

Answers: