XMLドキュメントの深さをカウントする方法(DOMの例)
Note
この質問はJNPフォーラムからのもので、calculate the depth of the entire XML documentの方法を尋ねています。
XMLの深さを取得するには、ノードを再帰的にループし、レベルを比較するだけです。これが、XMLファイルの最も深いレベルをカウントして表示するDOMパーサーの例です。
1. XMLファイル
/users/example/test.xml
yong mook kim example 1000000 29 123 low yin fong fong fong 500000
2. JavaとDOMの例
XMLUtil.java
package com.example;
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/example/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;
}
}
}
}
}
}
出力
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