How to count the depth of xml document (DOM example)
By:Roy.LiuLast updated:2019-08-18
Note
This question is from JNP forum, asking how to calculate the depth of the entire XML document.
This question is from JNP forum, asking how to calculate the depth of the entire XML document.
To get the depth of a XML, just loop the node recursively, and compare the level, that’s all.Here is a DOM parser example to count and show the deepest level of an XML file.
1. XML File
/users/mkyong/test.xml
<company> <staff id="1"> <firstname>yong</firstname> <lastname>mook kim</lastname> <nickname>mkyong</nickname> <salary>1000000</salary> <age>29</age> <extra> <test>123</test> </extra> </staff> <staff id="2"> <firstname>low</firstname> <lastname>yin fong</lastname> <nickname>fong fong</nickname> <salary>500000</salary> </staff> </company>
2. Java & DOM example
XMLUtil.java
package com.mkyong; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class XMLUtil { static int depthOfXML = 1; public static void main(String argv[]) { try { String filepath = "/users/mkyong/test.xml"; DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(filepath); Element elements = doc.getDocumentElement(); int level = 1; System.out.println(elements.getNodeName() + "[" + level + "]"); NodeList nodeList = elements.getChildNodes(); printNode(nodeList, level); System.out.println("The deepest level is : " + depthOfXML); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (SAXException sae) { sae.printStackTrace(); private static void printNode(NodeList nodeList, int level) { level++; if (nodeList != null && nodeList.getLength() > 0) { for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { System.out.println(node.getNodeName() + "[" + level + "]"); printNode(node.getChildNodes(), level); // how depth is it? if (level > depthOfXML) { depthOfXML = level;
Output
company[1] staff[2] firstname[3] lastname[3] nickname[3] salary[3] age[3] extra[3] test[4] staff[2] firstname[3] lastname[3] nickname[3] salary[3] The deepest level is : 4
References
From:一号门
Previous:ASCII Art Java example
COMMENTS