XPath 表达式中的粗体部分不是有效的谓词表达式。我只能猜测,你想达到什么目的。如果您只想要<command_details/>
元素,其<configScope/>
子元素的属性设置为inHierarchical="true"
,cookie="{COOKIE}"
那么dn="org-root"
XPath 表达式应该是:
/abcd/nsanity/component_details[@component='ucs']/command_details[configScope[@inHierarchical='true' and @cookie='{COOKIE}' and @dn='org-root']]/collected_data
这是一个示例 XML:
<abcd>
<nsanity>
<component_details component="ucs">
<command_details>
<configScope inHierarchical="true" cookie="{COOKIE}" dn="org-root" />
<collected_data>Yes</collected_data>
</command_details>
<command_details>
<configScope inHierarchical="true" cookie="{COOKIE}" dn="XXX"/>
<collected_data>No</collected_data>
</command_details>
</component_details>
</nsanity>
</abcd>
以下 Java 程序读取 XML 文件test.xml
并计算 XPath 表达式(并打印 element 的文本节点<collected_data/>
。
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class Test {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document document = dbf.newDocumentBuilder().parse("test.xml");
XPath xpath = XPathFactory.newInstance().newXPath() ;
NodeList nl = (NodeList) xpath.evaluate("/abcd/nsanity/component_details[@component='ucs']/command_details[configScope[@inHierarchical='true' and @cookie='{COOKIE}' and @dn='org-root']]/collected_data", document, XPathConstants.NODESET);
for(int i = 0; i < nl.getLength(); i++) {
Element el = (Element) nl.item(i);
System.out.println(el.getTextContent());
}
}
}