【发布时间】:2013-01-22 22:34:18
【问题描述】:
如果我有如下的 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
【问题讨论】:
-
return "//" + xmlTag怎么样? -
@ThreaT 你使用xpath从文档中获取节点,如果你一开始就有节点,为什么要把节点变成只能用来再次获取节点的xpath ?
-
return "(//" + xmlTag + ")[1]";怎么样? -
那个是节点在XML文档中的绝对路径。你是说你需要完整的路径,包括所有的父节点?如果是这样,你为什么需要它?