【问题标题】:get value from xml with r by attribute通过属性从带有r的xml中获取值
【发布时间】:2017-07-22 16:30:07
【问题描述】:

我正在尝试从 xml 获取如下所示的值:

<data>
    <result name="r">
        <item>
            <str name="id">123</str>
            <str name="xxx">aaa</str>
        </item>
        <item>
            <str name="id">456</str>
            <str name="xxx">aaa</str>
        </item>
    </result>
</data>

到目前为止,我可以通过以下方式获得id的值:

xmlfile <- xmlParse(url)
data <- xmlRoot(xmlfile) 
result <- xmltop[["result"]]
for (i in xmlSize(result)) {
  print(xmlValue(result[[i]][[1]]))
}

这似乎非常低效,并且仅当“id”存储在第一个子元素中时才有效。那么,有没有办法通过搜索属性(name)和值(id)来获取元素的值(123, 456)?

【问题讨论】:

    标签: r xml xml2


    【解决方案1】:

    xml2 包非常适合解决此类问题。

    library(xml2)
    page<-read_xml('<data>
        <result name="r">
                   <item>
                   <str name="id">123</str>
                   <str name="xxx">aaa</str>
                   </item>
                   <item>
                   <str name="id">456</str>
                   <str name="xxx">aaa</str>
                   </item>
                   </result>
                   </data>')
    
    #find all str nodes
     nodes<-xml_find_all(page, ".//str")
    #filter out the nodes where the attribute name=id
     nodes<-nodes[xml_attr(nodes, "name")=="id"]
    #get values (as character strings)
     xml_text(nodes)
    

    这一切都可以在一行代码中完成,但为清楚起见,步骤分为三个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-13
      • 1970-01-01
      相关资源
      最近更新 更多