从xml文件获取嵌套数据

时间:2013-07-22 13:49:54

标签: xml r

我有一个xml文件,其结构如下:

<?xml version="1.0" encoding="utf-8"?>
<ScheduleMessage DtdVersion="3" DtdRelease="0">
  <MessageIdentification v="ETSOVista-DMinus1TotalLoadForecast-DE-2012-1" />
  <MessageVersion v="1" />
  <MessageType v="A11" />
    <ScheduleTimeSeries>
    <SendersTimeSeriesIdentification v="10YCB-GERMANY--8" />
    <SendersTimeSeriesVersion v="1" />
    <BusinessType v="A05" />
    <Period>
      <TimeInterval v="2012-11-15T23:00Z/2012-11-16T23:00Z" />
      <Resolution v="PT60M" />
      <Interval>
        <Pos v="1" />
        <Qty v="52452" />
      </Interval>
      <Interval>
        <Pos v="2" />
        <Qty v="50527" />
      </Interval>
      <Interval>
       <Pos v="3" />
       <Qty v="49221" />
      </Interval>
      <Interval>
       <Pos v="4" />
       <Qty v="49344" />
      </Interval>
    </Period>
   </ScheduleTimeSeries>
   <ScheduleTimeSeries>
    <SendersTimeSeriesIdentification v="10YCB-GERMANY--8" />
    <SendersTimeSeriesVersion v="1" />
    <BusinessType v="A05" />
    <Period>
     <TimeInterval v="2012-11-16T23:00Z/2012-11-17T23:00Z" />
     <Resolution v="PT60M" />
     <Interval>
      <Pos v="1" />
      <Qty v="50935" />
     </Interval>
     <Interval>
      <Pos v="2" />
      <Qty v="48918" />
     </Interval>
     <Interval>
      <Pos v="3" />
      <Qty v="47347" />
     </Interval>
     <Interval>
      <Pos v="4" />
      <Qty v="46382" />
  </Interval>
 </Period>
</ScheduleTimeSeries>
</ScheduleMessage>

我只需要Qty个值。到目前为止,我的代码看起来像这样:

xml <- xmlInternalTreeParse(file = "test.xml")
xml_top <- xmlRoot(xml)
xml_children <- xmlChildren(x = xml_top)

但是当我尝试使用以下内容深入了解文件时

xml_children2 <- xmlChildren(x = xml_children)

我收到以下错误:

Error in UseMethod("xmlChildren") : 
no applicable method for 'xmlChildren' applied to an object of class "c('XMLInternalNodeList', 'XMLNodeList')"

我还尝试使用[][[]]对文件进行分组,但它总是引导我犯同样的错误。

2 个答案:

答案 0 :(得分:0)

使用XQuery处理器(例如xqilla

)会更简单
$ echo 'for $v in //Qty/@v return xs:string($v)' | xqilla -i test.xml /dev/stdin
52452
50527
49221
49344
50935
48918
47347
46382

然后可以使用read.table轻松读取输出。您也可以使用RXQuery包在R中运行此功能,或者如this answer所示。

致谢:AnswerExtract value of attribute node via XPath

答案 1 :(得分:0)

我通过使用:

解决了我的问题
xpathSApply(doc = xml_top, 
            file = "//ScheduleMessage/ScheduleTimeSeries/Period/Interval/Qty", 
            fun = xmlAttrs)