0

I am trying to write a piece of code that can parse any xml and print its contents. I am using DOM parser. I am able to get the name of the root tag of the xml, but cant obtain tag name of the immediate child. This can be done easily in case the node names are known by using the method 'getElementsByTagName' . Is there any way out of this dilemma ?

My code goes like this :

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
doc.getDocumentElement().getNodeName() // this gets me the name of the root node.

Now how can i get the name of the immediate child node so that i can traverse the xml using getElementsByTagName("x").

Thanks in advance.

1 Answer 1

3

getChildNodes() returns all children of an element. The list will contain more then just elements so you'll have to check each child node if it is an element:

NodeList nodes = doc.getDocumentElement().getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
  Node node = nodes.get(i);
  if (node instanceof Element) {
    Element childElement = (Element) node;
    System.out.println("tag name: " + childElement.getTagName());
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Maybe this has changed but shouldn't it be: nodes.item(i)
@Andreas_D ! I found two method in NodeList APIs. You can see docs.oracle.com/javase/7/docs/api/org/w3c/dom/NodeList.html . The point is that the method nodes.get(i); is not define in NodeList.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.