我有以下要解析的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
但未成功。
答案 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"/>