使用R在XML中的同一节点内的另一个属性中的值编辑属性的现有值

时间:2017-02-24 23:26:37

标签: r xml xml2

我有以下要解析的XML。重复的属性名称使我很难获得我想要的输出。

这个问题的一个显而易见的解决方案是改变属性得分的值。

      <linescore score="129">
        <quarter quarter="1" score="16"/>
        <quarter quarter="2" score="30"/>
        <quarter quarter="3" score="42"/>
        <quarter quarter="4" score="27"/>
        <quarter quarter="5" score="9"/>
        <quarter quarter="6" score="5"/>

您如何根据季度值更改分数值?例如:

      <linescore score="129">
        <quarter quarter="1" score="16_1"/>
        <quarter quarter="2" score="30_2"/>
        <quarter quarter="3" score="42_3"/>
        <quarter quarter="4" score="27_4"/>
        <quarter quarter="5" score="9_5"/>
        <quarter quarter="6" score="5_6"/>

我尝试使用xml_replace但未成功。

1 个答案:

答案 0 :(得分:1)

以这种方式:

library(xml2)
library(purrr)
xml <- read_xml('
<linescore score="129">
<quarter quarter="1" score="16"/>
<quarter quarter="2" score="30"/>
<quarter quarter="3" score="42"/>
<quarter quarter="4" score="27"/>
<quarter quarter="5" score="9"/>
<quarter quarter="6" score="5"/>
</linescore>')
xml %>% 
  xml_find_all("/linescore/quarter") %>% 
  walk(~xml_set_attr(.x, "score", paste(xml_attrs(.x)[c("score", "quarter")], collapse ="_"))) 
xml  
# xml_document}
# <linescore score="129">
# [1] <quarter quarter="1" score="16_1"/>
# [2] <quarter quarter="2" score="30_2"/>
# [3] <quarter quarter="3" score="42_3"/>
# [4] <quarter quarter="4" score="27_4"/>
# [5] <quarter quarter="5" score="9_5"/>
# [6] <quarter quarter="6" score="5_6"/>