2017-07-22 45 views
1

我試圖獲取值從xml,看起來像這樣得到的值:從其中r通過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)?

回答

0

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) 

這一切都可以在一行代碼中完成,但爲了清晰起見,這些步驟被分成三部分。