Alex2330 Alex2330 - 1 month ago 5
Java Question

How to read XML file in Java without tagName

I need to read a file xml in java , the xmd document looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<Provider>
<Invoice>256848</Invoice>
<InvoiceType>Paper</InvoiceType>
<Phone>0554334434</Phone>
<InvoiceDate>20091213</InvoiceDate>
<CustomerRequest>
<Article>
<ArticleCode>PE4</ArticleCode>
<ArticleDescription>Pen</ArticleDescription>
<DeliveryDate>20091231</DeliveryDate>
<Price>150</Price>
</Article>
</CustomerRequest>
<CustomerInfo>
<CustomerID>6901</CustomerID>
<CustomerAddress> Houghton Street</CustomerAddress>
<CustomerCity>London</CustomerCity>
</CustomerInfo>

</Provider>


The problem is that the content of the document can change, by including others tags and many nested tags which can have random level, is there a way to have all tags and values of the document
in a dynamic way without specifying the tag name?
Thanks

Answer

Because of that XML is build as a tree, you need to use a recursion:

Assume this is your main class:

public static void main(String[] args) throws SAXException, IOException,
        ParserConfigurationException, TransformerException {

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
        .newInstance();
    DocumentBuilder doc = docBuilderFactory.newDocumentBuilder();
    Document document = doc.parse(new File("doc.xml"));
    childRecusrsion(document.getDocumentElement());
}

And this is the recursion:

  public static void childRecusrsion(Node node) {
        // do something with the current node instead of System.out
        System.out.println(node.getNodeName());

        NodeList nodeList = node.getChildNodes(); //gets the child nodes that you need
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node currentNode = nodeList.item(i);
            if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
                //call the recursion
                childRecusrsion(currentNode);
            }
        }
    }
Comments