【问题标题】:How to craft an xpath so it includes not only the full xpath, but also the value in the child element that is referred to如何制作 xpath,使其不仅包含完整的 xpath,还包含引用的子元素中的值
【发布时间】:2012-05-04 15:41:33
【问题描述】:

我整天都在努力解决这个问题......也许你可能知道方法。

我正在尝试制作一个 XPATH,它由一个明确且明确的 xpath 以及所引用的叶子元素中的数据项组成。

/bookstore[3]/book[4]/title 将是 xpath 的一个很好的例子。

这应该返回三号书店中四号书的标题。假设这很好,

但是,我想在其中嵌入标题 - 无论我尝试哪种方式,它似乎都会出错。目的是在我的应用程序中创建一个有效 xpath 的错误代码 - 并显示违规项目的位置和值。

所以,显而易见的第一次尝试是:

/bookstore[3]/book[title="oxford dictionary]/title

虽然这很好,但书店有数百本牛津词典,我只想要 4 号。

所以我尝试了很多变体,比如这些......并且都没有通过在线语法检查器。

/bookstore[3]/book[[4] and title="oxford dictionary]/title
/bookstore[3]/book[4]/title | /bookstore[3]/book[title=oxford dictionary]/title

欢迎任何关于如何在叶子元素中包含显式 XPATH 和附加内容的建议。

此致,CR。

【问题讨论】:

  • 当只有一个根元素时,你怎么能拥有/bookstore[3]

标签: xml xpath


【解决方案1】:
  1. 要获取标签正文中的文本内容,您可以使用 /bookstore/book[@title="oxford dictionary"][4]/title/text()

  2. 要获取标签属性的文本内容,您可以使用 /bookstore/book[@title="oxford dictionary"][4]/attribute::name

第一个表达式将返回“Some Text 4”,使用下面的 xml 进行评估。
第二个表达式将返回“title4”,使用下面的 xml 进行评估。

<bookstore>
    <book title="oxford dictionary">
        <title name="title1">Some Title 1</title>
    </book>
    <book title="oxford dictionary">
        <title name="title2">Some Title 2</title>
    </book>
    <book title="oxford dictionary">
        <title name="title3">Some Title 3</title>
    </book>
    <book title="oxford dictionary">
        <title name="title4">Some Title 4</title>
    </book>
</bookstore>

【讨论】:

    猜你喜欢
    • 2016-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-14
    • 1970-01-01
    • 2011-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多