【问题标题】:xpath not accepting this expressionxpath 不接受这个表达式
【发布时间】:2013-05-15 13:57:45
【问题描述】:

大家好,我有关于 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:应有位置路径,但遇到以下标记:

【问题讨论】:

  • 请向我们展示数据示例并正确格式化代码(您的查询中是否包含星号?)。阅读FAQ,了解如何格式化您的帖子。
  • 没有星号不包含在我的查询中,只有 符号抛出异常
  • 如果下面的答案不符合您的期望,请重新考虑我在之前的评论中发布的内容。事实上,这个问题很模糊。 “我的查询中没有星号”是什么意思?

标签: java xpath expression


【解决方案1】:

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 表达式(并打印元素 &lt;collected_data/&gt; 的文本节点。

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());
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-24
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2019-06-24
    相关资源
    最近更新 更多