开发者

Child node name in a xml

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.getDocu开发者_开发技巧mentElement().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.


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());
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜