0

大家好,我有关于 xpath 的问题

/abcd/nsanity/component_details[@component="ucs"]/command_details[ <* configScope inHierarchical="true" cookie="{COOKIE}" dn="org-root" * /> ]/collected_data

我想检索 xpath 语句上方的字符串,但是当我将此 xpath 提供给 xpath 表达式以进行评估时,它会引发异常,例如

原因:javax.xml.transform.TransformerException:应有位置路径,但遇到以下标记:<configScope

4

1 回答 1

2

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());
    }
  }
}
于 2013-05-15T15:33:49.267 回答