使用R将信息放在方括号内时,如何解析XML文件的特定信息?

时间:2019-06-18 21:09:24

标签: r xml dataframe xml-parsing

我正在使用R,并且试图将信息从XML文件解析为DataFrame。问题是,当信息位于方括号之间时,我知道该怎么做: <Person><Name> Marcos </Name></Person> 但是我正在使用的XML在方括号内提供了信息,作为一个属性:

<Games timestamp="2017-08-29T15:26:24">
  <Game id="942799" away_score="0" away_team_id="449" away_team_name="Villarreal" competition_id="23" competition_name="Spanish La Liga" game_date="2017-08-21T19:15:00" home_score="1" home_team_id="855" home_team_name="Levante" matchday="1" period_1_start="2017-08-21T19:15:40" period_2_start="2017-08-21T20:18:02" season_id="2017" season_name="Season 2017/2018">
    <Event id="1615184504" event_id="1" type_id="34" period_id="16" min="0" sec="0" team_id="855" outcome="1" x="0.0" y="0.0" timestamp="2017-08-21T18:10:10.82" last_modified="2017-08-21T19:16:17" version="1503339377339">
      <Q id="2065887850" qualifier_id="227" value="0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0" />
      <Q id="2021905255" qualifier_id="30" value="49214, 105525, 77039, 152551, 90400, 169201, 88952, 196739, 91953, 163784, 165375, 78323, 54224, 49442, 181859, 42844, 194764, 83564" />
      <Q id="1295835216" qualifier_id="59" value="1, 2, 3, 8, 15, 6, 24, 10, 17, 23, 11, 5, 7, 13, 14, 19, 21, 22" />
      <Q id="1289404134" qualifier_id="44" value="1, 2, 2, 3, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5" />
      <Q id="1475702012" qualifier_id="130" value="4" />
      <Q id="1510724498" qualifier_id="197" value="1584" />
      <Q id="1735470938" qualifier_id="194" value="165375" />
      <Q id="1307709006" qualifier_id="131" value="1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 0, 0, 0, 0, 0, 0" />
    </Event>
  </Game>
</Games>

您能帮我处理这些信息吗?例如,我需要提取qualifier_id和值。

谢谢。

2 个答案:

答案 0 :(得分:1)

您可以从xml_attrs()包中使用xml_attr()xml2,如下所示:

library(xml2)
x <- "test.xml"
X <- read_xml(x)
xml_attr(X, attr = "timestamp")
xml_attrs(X)
xml_attr(xml_children(X), attr = "id")
xml_attrs(xml_children(X))

有关更多示例,请参见文档

答案 1 :(得分:1)

我直到最近才意识到,使用 XML 库可以简单地将XPath string传入进行选择并返回所有值的列表。例如:

library(XML)
x <- xmlInternalTreeParse("file.xml")

x["//Games//Event//Q//@qualifier_id"]

x["//Games//Event//Q//@value"]


str(x["//Games//Event//Q//@qualifier_id"])
#List of 8
# $ :Class 'XMLAttributeValue'  Named chr "227"
#  .. ..- attr(*, "names")= chr "qualifier_id"
# $ :Class 'XMLAttributeValue'  Named chr "30"
#  .. ..- attr(*, "names")= chr "qualifier_id"
#...