2013-08-29 126 views
0

如果我有以下示例中的list.db[[1]]這樣的列表,我如何才能讀出<part的所有屬性?我如何選擇一個沒有子節點的節點?如何訪問XML標籤的屬性

require(XML) 

txt = "<doc> 
     <part name=\"abc\"> 
      <name>ABC</name> 
      <type>XYZ</type> 
      <cost>3.54</cost> 
      <status>available</status> 
     </part> 
     <part> 
      <name>ABC</name> 
      <type>XYZ</type> 
      <cost>3.54</cost> 
      <status>available</status> 
     </part> 
     </doc>" 

tree <- xmlTreeParse(txt, useInternalNodes = TRUE) 
list.db <- getNodeSet(tree, "//part") 
list.db[[1]][1:2] 
xmlRoot(list.db[[1]])[1] 

回答

1

您可以使用xmlAttrs功能:

xmlAttrs(list.db[[1]]) 
# name 
#"abc" 

或者你可以通過xpathSApply使用XPath語法:

xpathSApply(tree, "//part/@name") 
# name 
#"abc"