以下のようなXMLドキュメントがある場合:
<foo>
<foo1>Foo Test 1</foo1>
<foo2>
<another1>
<test10>This is a duplicate</test10>
</another1>
</foo2>
<foo2>
<another1>
<test1>Foo Test 2</test1>
</another1>
</foo2>
<foo3>Foo Test 3</foo3>
<foo4>Foo Test 4</foo4>
</foo>
<test1>
たとえば、のXPathを取得するにはどうすればよいですか?したがって、出力は次のようになります。foo/foo2[2]/another1/test1
コードは次のようになると思います。
public String getXPath(Document document, String xmlTag) {
String xpath = "";
...
//Get the node from xmlTag
//Get the xpath using the node
return xpath;
}
としましょうString XPathVar = getXPath(document, "<test1>");
。次のコードで機能する絶対xpathを取得する必要があります。
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression xpr = xpath.compile(XPathVar);
xpr.evaluate(Document, XPathConstants.STRING);
//test1
ただし、メタデータの目的でも使用されるため、のようなショートカットにすることはできません。
結果を次の方法で印刷する場合:
System.out.println(xpr.evaluate(Document, XPathConstants.STRING));
ノードの値を取得する必要があります。それで、もしそうならXPathVar = foo/foo2[2]/another1/test1
、私は戻るべきです:
Foo Test 2
ではなくThis is a duplicate