使用R将xml解析为数据帧

时间:2017-08-16 08:11:57

标签: r xml

我确信这个问题已被多次回答......但是我猜的数据有点独特。以下是我的数据集的一部分。

<?xml version="1.0" encoding="UTF-8"?>
<IOTModellerLog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" DeviceID="7430180" ClientID="12324" FileCreationDate="2017-03-01T22:40:03" FileVersion="2" EventClassID="65535" IOTLogCreationDate="2017-03-01T12:29:54" SampleID="1" xsi:noNamespaceSchemaLocation="/opt/nds/ams_proxy/webapps/ams_proxy/WEB-INF/amsXmlSchema.xsd">
   <Event EventTime="2017-02-27T18:33:58">
      <IOTEvent State="PowerOn" />
   </Event>
   <Event EventTime="2017-02-28T08:59:03">
      <DataEvent>
         <Model>1</Model>
         <DataType>1</DataType>
         <DataValue>0301</DataValue>
      </DataEvent>
   </Event>
   <Event EventTime="2017-02-28T08:59:13">
      <DataEvent>
         <Model>1</Model>
         <DataType>1</DataType>
         <DataValue>0401</DataValue>
      </DataEvent>
   </Event>
</IOTModellerLog>

我正在尝试将其转换为第一列为EventTime的数据框。预期的格式如下:

EventTime             Model    DataType    DataValue
2017-02-28T08:59:13     1        1           0401
2017-02-28T08:59:15     1        5           070707

我尝试了以下内容:

result <- xmlParse("demoxml.xml")
XML:::xmlAttrsToDataFrame(result["//Event"])  #This just prints only the time

xmlToDataFrame(nodes=getNodeSet(result,"//DataEvent"))[c("Model","DataType","DataValue")]

我不知道如何将EventEvent值与EventTime一起获取并将其放在data.frame中。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

我使用过这样的东西

 for( i = 0; i < markers.length; i++ ) {
     var position = new google.maps.LatLng(markers[i][0], markers[i][1]);
     var icon = {url:"http:///".concat(markers[i][3]),
                 scaledSize: new google.maps.Size(20, 20), // scaled size
                 origin: new google.maps.Point(0,0), // origin
                 anchor: new google.maps.Point(0, 0) };
     marker = new google.maps.Marker({
         position: position,
         map: map,
         title: markers[i][4].toString().concat(' ').concat(markers[i][5].toString()),
         icon: icon, 
         url:'im:<sip:'+markers[i][6]+'>'
     });
     var infowindow = new google.maps.InfoWindow({
                content: ''
     });
     marker.addListener('mouseover', function() { 
        infowindow.setContent('<p><label>Name:</label> '+this.title+'</p>' +
                              '<center><button class="btn btn-primary" \n\
                             onclick="window.location.assign(' + this.url + ');">Call</button></center>'); 
        infowindow.open(map, this);
    });

结果如下所示

library(XML)
library(data.table)
result <- xmlParse('text_XML.xml')
result_nodes = XML::getNodeSet(result , "//IOTModellerLog/Event")
rbindlist(lapply(result_nodes,function(x) data.frame(as.list(unlist(xmlToList(x))))),use.names = TRUE, fill = TRUE)

我认为这是你可以使用的东西:)