Load XML to DataFrame in R

2019-05-26 13:19发布

问题:

I am new to R programming and trying to load a simple XML. I tried

data <- xmlToDataFrame("temp.xml")

but got this error

Error in xmlToDataFrame(xmlParse(doc), colClasses, homogeneous, collectNames, : error in evaluating the argument 'doc' in selecting a method for function 'xmlToDataFrame': Error: XML content does not seem to be XML: 'temp.xml'`

XML Schema

<root>
  <row Id="1" UserId="1" Name="Rohit" Date="2009-06-29T10:28:58.013" />
  <row Id="2" UserId="3" Name="Rohit" Date="2009-06-29T10:28:58.030" />
</root>

Also I tried:

xml <- xmlParse("temp.xml")

Output:

Error: XML content does not seem to be XML: 'temp.xml'

My XML file is in same working directory.

Also if you want to try, I have uploaded the sample XML here: http://www4.ncsu.edu/~rkandha/temp.xml
Please provide some direction on which function I should use here.

回答1:

This should work:

text ='<root>
  <row Id="1" UserId="1" Name="Rohit" Date="2009-06-29T10:28:58.013" />
  <row Id="2" UserId="3" Name="Rohit" Date="2009-06-29T10:28:58.030" />
</root>'

library(XML)
do.call(rbind,xmlToList(xmlParse(file=text,asText=TRUE)))
    Id  UserId Name    Date                     
row "1" "1"    "Rohit" "2009-06-29T10:28:58.013"
row "2" "3"    "Rohit" "2009-06-29T10:28:58.030"