昨日この質問をしたところ、Super Chafouin Java: How to get xml nodes pathから大きな助けを得ました。
でも。ここでは再帰を使用できません。再帰なしで同じ仕事をする方法はありますか? 私は本当にこれについて助けが必要です。前もって感謝します。
昨日この質問をしたところ、Super Chafouin Java: How to get xml nodes pathから大きな助けを得ました。
でも。ここでは再帰を使用できません。再帰なしで同じ仕事をする方法はありますか? 私は本当にこれについて助けが必要です。前もって感謝します。
他のコメントは、同じロジックを何度もコピーしているため、私には奇妙に見えます。
DOM を使用している場合、再帰を使用しないのは難しいことです。ただし、他の種類の XML パーサーもあります。
あなたの仕事は、StAX パーサーを使えば簡単です (SAX の使用も同様に簡単だと思います)。
アイデアは簡単です:
命令は十分に明確である必要があり、平均的なプログラマーは上記のロジックによって実際のコードを理解できるはずです。
私の見解:
// create a document
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
Document document = domFactory.newDocumentBuilder().parse("input.xml");
// XPath selecting all leaf nodes (assumes all leaf nodes contain a value)
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("//*[count(./descendant::*)=1]");
// list of all nodes containing a value
NodeList list = (NodeList)expr.evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < list.getLength(); i++) {
// store node name and value
Node node = list.item(i);
StringBuilder path = new StringBuilder(node.getNodeName());
String value = node.getTextContent();
// traverse all parents and prepend their names to path
node = node.getParentNode();
while (node.getNodeType() != Node.DOCUMENT_NODE) {
path.insert(0, node.getNodeName() + '.');
node = node.getParentNode();
}
System.out.println(path + " = " + value);
}