【问题标题】:Conditional Retrieval of XML Nodes with XML2 package in R在 R 中使用 XML2 包条件检索 XML 节点
【发布时间】:2020-07-11 12:56:01
【问题描述】:

我正在尝试使用 xml2 包来检索和过滤 R 中的 XML 节点。

我有一个带有结构的 XML 文件...

...
 <entry>
  <feature type="x">123</feature>
  <feature type="y">456</feature>
  <feature type="y">789</feature>
 </entry>
...

...我试图在单个语句中检索只是类型为“y”的第一个“特征”。

目前我正在这样做:

# Return all <feature> nodes
xmlNodes <- xml_find_all(inputXml, ".//entry/feature")

# ...filter by type="y"...
xmlNodes <- xmlNodes[xml_attr(xmlNodes, "type")=="y"]

# ...and then return the first node
xmlNode <- xmlNodes[1]

是否有更简单的方法可以在单个语句中实现这一点,也许使用带有“type”==“y”条件的 xml_find_first() 函数,假设第一个特征节点可能不一定是“type” =“y”?

可能是这样的:

xmlNode <- xml_find_first(inputXml, ".//entry/feature" & xml_attr(inputXml, "type")=="chain")

我觉得这是一个非常简单的问题,但我是 R 新手,对所有语法都不太熟悉...非常感谢!

【问题讨论】:

    标签: r xml2


    【解决方案1】:

    这是关于 xpath 语法,而不是 R 语法。您的示例本身不是一个有效的 xml 文档来演示,因此我对其进行了一些扩展:

    xml <- '<?xml version="1.0"?>
    <entries>
    <entry>
        <feature type="x">123</feature>
        <feature type="y">456</feature>
        <feature type="y">789</feature>
    </entry>
    <entry>
        <feature type="x">12</feature>
        <feature type="y">13</feature>
        <feature type="y">14</feature>
    </entry>
    </entries>'
    

    如果我理解正确,您希望每个entry 中的type = "y" 中的第一个feature,因此在我的示例中,这将是包含文本“456”和“13”的节点。在这种情况下,正确的 xpath 表达式是 "//feature[@type = 'y'][1]"

    所以你会得到正确的节点:

    xml2::read_xml(xml) %>% xml2::xml_find_all("//feature[@type = 'y'][1]")
    #> {xml_nodeset (2)}
    #> [1] <feature type="y">456</feature>
    #> [2] <feature type="y">13</feature>
    

    【讨论】:

    • 太棒了,我没有意识到 Xpath 表达式能够接受这样的条件语句......我将不得不阅读它。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多