Alex2330 Alex2330 - 1 year ago 53
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"?>
<CustomerAddress> Houghton Street</CustomerAddress>


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?

Answer Source

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
    DocumentBuilder doc = docBuilderFactory.newDocumentBuilder();
    Document document = doc.parse(new File("doc.xml"));

And this is the recursion:

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

        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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download