【问题标题】:xpath: How to select Parent Element with conditions on Multiple Child Elements?xpath:如何选择具有多个子元素条件的父元素?
【发布时间】:2019-08-25 04:20:54
【问题描述】:

我正在使用 R 中的“xml2”库来读取 xml 文件以进行数据分析。

在下面的示例xml中,如何返回子元素满足多个条件的父'row'元素?

我想选择“year”元素等于“2018”且“vehicle_type”元素等于“scooter”的“row”元素?

<rows>
    <row>
      <vehicle_type>scooter</vehicle_type>
      <year>2018</year>
      <trip_duration>358</trip_duration>
    </row>
    <row>
      <vehicle_type>scooter</vehicle_type>
      <year>2019</year>
      <trip_duration>358</trip_duration>
    </row>
    <row>
      <vehicle_type>bicycle</vehicle_type>
      <year>2018</year>
      <trip_duration>358</trip_duration>
    </row>
</rows>

我使用了“|”符号作为 AND 运算符。但是,它返回一个错误。

这是我目前尝试的代码:

library(xml2)
library(selectr)
tripXML <- read_xml('trips-1.xml')

rows <- xml_find_all(tripXML, "//row[./year/text()='2018' | ./vehicle_type/text()='scooter']")

这是 RStudio 中的错误消息。

Error in xpath_search(x$node, x$doc, xpath = xpath, nsMap = ns, num_results = Inf) : xmlXPathEval: 3 object left on the stack

我想选择这个行值:

<row>
      <vehicle_type>scooter</vehicle_type>
      <year>2018</year>
      <trip_duration>358</trip_duration>
</row>

希望有人能帮忙,非常感谢。

【问题讨论】:

    标签: r xpath xml2


    【解决方案1】:

    | 运算符不是 XPath 中的 and 运算符,而是 merge nodeset 运算符(Look here at W3Schools 以获得一些灵感)。因此,要清理您的表达式,只需使用 and 运算符:

    //row[year/text()='2018' and vehicle_type/text()='scooter']
    

    然后你会得到你想要的输出。
    (我还删除了领先的./,因为它们不是必需的)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-05
      相关资源
      最近更新 更多