xpath不接受此表达式

时间:2013-05-15 13:57:46

标签: java xpath expression

大家好我对xpath的问题

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

我想检索xpath语句之上的字符串但是当我将此xpath提供给evaulate的xpath表达式时,它会抛出异常,如

引起:javax.xml.transform.TransformerException:需要位置路径,但遇到以下标记:< configScope

1 个答案:

答案 0 :(得分: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表达式(并打印元素<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());
    }
  }
}