DEV Community

Mahesh K
Mahesh K

Posted on • Updated on

R Language : Read XML files In R

Let's discuss how to Read XML Files in R. There are many places where people make use of the XML data. Often some specific set of data is being stored into the XML.

Prior to JSON files getting popular as they are today, many companies used to offer the XML export option. So you are going to find many legacy files that store the data in XML file. So we are going to see how to read this data with the R language.

You can watch the video instruction of the tutorial - How to Read XML Files in R.

XML Package

In order to read the XML file and to manipulate the data, you need to make use of the XML package. You can install the package with the following code.

install.packages("XML")
Enter fullscreen mode Exit fullscreen mode

So let's assume we have XML file named mydata.xml. You can get the XML data from sample file.

Now we can get started to import the package.

library("XML")
Enter fullscreen mode Exit fullscreen mode

Next package that we would be needing to be added is the following.

library("methods")
Enter fullscreen mode Exit fullscreen mode

Let's name the input file and import the file.

dt <- xmlParse(file = "mydata.xml")
Enter fullscreen mode Exit fullscreen mode

So here's the data variable named "dt". You can print the output as follows.

print(dt)
Enter fullscreen mode Exit fullscreen mode

Here's the output that you'd get in the console.

<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<calories>650</calories>
</food>
</breakfast_menu>
Enter fullscreen mode Exit fullscreen mode

I hope this post helps you to read the XML data from the file in R language.

Top comments (1)

Collapse
 
mccurcio profile image
Matt Curcio

Good start, but how does one get the specific information? How do you choose the info would be good to add too. :))
Thanks