使用R为xml文件中的所有节点提取具有相同名称的属性

时间:2019-06-26 20:09:28

标签: r xml2

我正在尝试提取xml文件中的所有属性(具有相同的名称)。当前使用xml2软件包,并希望通过xml_attrxml_attrs函数获得成功。

library(xml2)

# basic xml file
x <- read_xml("<a>
  <b><c>123</c></b>
  <b><c>456</c></b>
</a>")

# add a few attributes with the same name of "Fake ID"
xml_set_attr(xml_child(x, 'b[1]'), 'FakeID', '11111')
xml_set_attr(xml_child(x, 'b[2]'), 'FakeID', '22222')
xml_set_attr(xml_child(xml_child(x, 'b[2]'), 'c'), 'FakeID', '33333')

# this will give me attributes only when I call a specific child node
xml_attr(xml_child(x, 'b[1]'), 'FakeID')
# this does not give me any attributes with the name "FakeID" because the current node
#   doesn't have that attribute
xml_attr(x, 'FakeID')

我最终希望的是一个向量,该向量给出xml中具有属性“ FakeID”的每个节点的值; c('11111', '22222', '33333')

1 个答案:

答案 0 :(得分:1)

我使用了软件包rvest,因为它重新导出了xml2函数,但也重新导出了%>%运算符。然后,我将您的xml用作字符串以弄清楚其中的内容,并向您的第一个节点添加了第二个属性。

xml_nodes()中,我使用* css选择器选择所有节点,并指定我只希望具有[FakeID]且具有FakeID属性的节点。

library(rvest)

"<a>
   <b FakeID=\"11111\" RealID=\"abcde\">
     <c>123</c>
   </b>
   <b FakeID=\"22222\">
     <c FakeID=\"33333\">456</c>
   </b>
</a>" %>% 
  read_xml() %>% 
  xml_nodes("*[FakeID]") %>% 
  xml_attrs() %>% 
  pluck("FakeID") %>% 
  unlist()