【问题标题】:How to parse specific information of a XML file when the information is inside the brackets using R?当信息在使用R的括号内时,如何解析XML文件的特定信息?
【发布时间】:2019-06-18 21:09:24
【问题描述】:

我正在使用 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 和 value。

提前致谢。

【问题讨论】:

    标签: r xml dataframe xml-parsing


    【解决方案1】:

    您可以像这样使用xml2 包中的xml_attrs()xml_attr()

    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))
    

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

    【讨论】:

      【解决方案2】:

      我最近才意识到可以使用 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"
      #...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-12-28
        • 1970-01-01
        • 1970-01-01
        • 2011-05-19
        • 1970-01-01
        • 1970-01-01
        • 2011-08-03
        相关资源
        最近更新 更多