1

I am trying to create a data frame from a xml file. I want the data frame to look like:

ID   TagName   Count
1     bob        12
2     Sue        52
3     carl       15

This is my code so far:

doc<-xmlTreeParse("data.xml", useInternal = TRUE)

rootNode<-xmlRoot(doc)

The file looks like (I couldn't use arrows for some reason):

<tag>

   <row Id = "1" TagName= "bob" Count = "12" />

   <row Id = "2" TagName= "Sue" Count = "52" />

   <row Id = "3" TagName= "carl" Count= "15" />

any help will be appreciated.

Will
  • 24,082
  • 14
  • 97
  • 108
  • 1
    Have you tried `xmlToList`? http://stackoverflow.com/questions/17198658/how-to-parse-xml-to-r-data-frame – Roman Luštrik Jul 20 '15 at 08:23
  • yes, I did , but I guess I am not good at pulling items out from a list. So the difficulty was for me to extract from the list that was created. – William Clarke Jul 22 '15 at 16:23

1 Answers1

0

Try this:

library(XML)
xml <- '<tag>
<row Id = "1" TagName= "bob" Count = "12" />
<row Id = "2" TagName= "Sue" Count = "52" />
<row Id = "3" TagName= "carl" Count= "15" />
</tag>'
as.data.frame(t(xpathSApply(xmlParse(xml), '/tag/*', xmlAttrs)))
#   Id TagName Count
# 1  1     bob    12
# 2  2     Sue    52
# 3  3    carl    15
lukeA
  • 53,097
  • 5
  • 97
  • 100