The Wayback Machine - https://web.archive.org/web/20240910130350/https://www.geeksforgeeks.org/working-with-xml-files-in-r-programming/
Open In App

Working with XML Files in R Programming

Last Updated : 01 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

XML which stands for Extensible Markup Language is made up of markup tags, wherein each tag illustrates the information carried by the particular attribute in the XML file. We can work with the XML files using the XML package provided by R. The package has to be explicitly installed using the following command: 

install.packages("XML")

Creating XML file

XML files can be created by saving the data with the respective tags containing information about the content and saving it with ‘.xml’.
We will use the following XML file ‘sample.xml’ to see the various operations that can be performed on the file:

HTML




<RECORDS>
  <STUDENT>
      <ID>1</ID>
      <NAME>Alia</NAME>
      <MARKS>620</MARKS>
      <BRANCH>IT</BRANCH>
  </STUDENT>
  <STUDENT>
      <ID>2</ID>
      <NAME>Brijesh</NAME>
      <MARKS>440</MARKS>
      <BRANCH>Commerce</BRANCH>
   </STUDENT>
  <STUDENT>
      <ID>3</ID>
      <NAME>Yash</NAME>
      <MARKS>600</MARKS>
      <BRANCH>Humanities</BRANCH>
   </STUDENT>
  <STUDENT>
      <ID>4</ID>
      <NAME>Mallika</NAME>
      <MARKS>660</MARKS>
      <BRANCH>IT</BRANCH>
   </STUDENT>
  <STUDENT>
      <ID>5</ID>
      <NAME>Zayn</NAME>
      <MARKS>560</MARKS>
      <BRANCH>IT</BRANCH>
   </STUDENT>
</RECORDS>


Reading XML File

The XML file can be read after installing the package and then parsing it with xmlparse() function, which takes as input the XML file name and prints the content of the file in the form of a list. The file should be located in the current working directory. An additional package named ‘methods’ should also be installed. The following code can be used to read the contents of the file “sample.xml”. 

Python3




# loading the library and other important packages
library("XML")
library("methods")
 
# the contents of sample.xml are parsed
data <- xmlParse(file = "sample.xml")
 
print(data)


Output:

1
Alia
620
IT
2
Brijesh
440
Commerce
3
Yash
600
Humanities
4
Mallika
660
IT
5
Zayn
560
IT

Extracting information about the XML file

XML files can be parsed and operations can be performed on its various components. There are various in-built functions available in R, to extract the information of the nodes associated with the file, getting the number of nodes in the file, and also the specific attributes of some particular node in the file. 

Python3




# loading the library and other important packages
library("XML")
library("methods")
 
# the contents of sample.xml are parsed
# Load the packages required to read XML files.
library("XML")
library("methods")
 
# Give the input file name to the function.
res <- xmlParse(file = "sample.xml")
 
# Extract the root node.
rootnode <- xmlRoot(res)
 
# number of nodes in the root.
nodes <- xmlSize(rootnode)
 
# get entire contents of a record
second_node <- rootnode[2]
 
# get 3rd attribute of 4th record
attri <- rootnode[[4]][[3]]
 
cat('number of nodes: ', nodes)
print ('details of 2 record: ')
print (second_node)
 
# prints the marks of the fourth record
print ('3rd attribute of 4th record: ', attr)


Output:

[1] number of nodes: 5
[2] details of 2 record:
$STUDENT
    2
    Brijesh
    440
    Commerce
[3] 3rd attribute of 4th record: 660

Conversion of XML to dataframe

In order to enhance the readability of the data, the XML data can be converted into a data frame consisting of a data frame comprising of rows and columns. R contains an in-built function xmlToDataFrame() which contains as input the XML file and outputs the corresponding data in the form of a data frame. This simulates the easy handling and processing of large amounts of data. 

Python3




# Load the required packages.
library("XML")
library("methods")
 
# Convert the input xml file to a data frame.
dataframe <- xmlToDataFrame("sample.xml")
print(dataframe)


Output:

       ID   NAME     MARKS      BRANCH       
1      1    Alia      620         IT
2      2    Brijesh   440      Commerce
3      3    Yash      600      Humanities
4      4    Mallika   660         IT
5      5    Zayn      560         IT

 



Previous Article
Next Article

Similar Reads

Working with Excel Files in R Programming
Excel files are of extension .xls, .xlsx and .csv(comma-separated values). To start working with excel files in R Programming Language, we need to first import excel files in RStudio or any other R supporting IDE(Integrated development environment). Reading Excel Files in R Programming Language First, install readxl package in R to load excel files
3 min read
Working with Binary Files in R Programming
In the computer science world, text files contain data that can easily be understood by humans. It includes letters, numbers, and other characters. On the other hand, binary files contain 1s and 0s that only computers can interpret. The information stored in a binary file can't be read by humans as the bytes in it translate to characters and symbol
5 min read
Working with JSON Files in R Programming
JSON stands for JavaScript Object Notation. These files contain the data in human readable format, i.e. as text. Like any other file, one can read as well as write into the JSON files. In order to work with JSON files in R, one needs to install the "rjson" package. The most common tasks done using JSON files under rjson packages are as follows: Ins
4 min read
Working with CSV files in R Programming
In this article, we will discuss how to work with CSV files in R Programming Language. R CSV Files R CSV Files are text files wherein the values of each row are separated by a delimiter, as in a comma or a tab. In this article, we will use the following sample CSV file. Getting and Setting the Working Directory with R CSV Files C/C++ Code # Get the
4 min read
Working with Databases in R Programming
Prerequisite: Database Connectivity with R Programming In R programming Language, a number of datasets are passed to the functions to visualize them using statistical computing. So, rather than creating datasets again and again in the console, we can pass those normalized datasets from relational databases. Databases in R Programming Language R can
4 min read
List all the Objects present in the Current Working Directory in R Programming - ls() Function
ls() function in R Language is used to list the names of all the objects that are present in the working directory. Syntax: ls() Parameters: This function needs no argument Example 1: # R program to list all the object names # Creating a vector vec &lt;- c(1, 2, 3) # Creating a matrix mat &lt;- matrix(c(1:4), 2) # Creating an array arr &lt;- array(
1 min read
Working with Sparse Matrices in R Programming
Sparse matrices are sparsely populated collections of elements, where there is a very less number of non-null elements. Storage of sparsely populated data in a fully dense matrix leads to increased complexities of time and space. Therefore, the data structures are optimized to store this data much more efficiently and decrease the access time of el
9 min read
Data Wrangling in R Programming - Working with Tibbles
R is a robust language used by Analysts, Data Scientists, and Business users to perform various tasks such as statistical analysis, visualizations, and developing statistical software in multiple fields.In R Programming Language Data Wrangling is a process of reimaging the raw data to a more structured format, which will help to get better insights
6 min read
Which Working Profiles Required R Programming Language?
R programming language is essential in various professional profiles that involve statistical analysis, data visualization, data manipulation, and report generation. Key roles that require proficiency in R include data scientists, statisticians, economists, biostatisticians, and data analysts, particularly in sectors like healthcare, finance, acade
3 min read
Reading Files in R Programming
So far the operations using the R program are done on a prompt/terminal which is not stored anywhere. But in the software industry, most of the programs are written to store the information fetched from the program. One such way is to store the fetched information in a file. So the two most common operations that can be performed on a file are: Imp
9 min read
Reading Tabular Data from files in R Programming
Often, the data which is to be read and worked upon is already stored in a file but is present outside the R environment. Hence, importing data into R is a mandatory task in such circumstances. The formats which are supported by R are CSV, JSON, Excel, Text, XML, etc. The majority of times, the data to be read into R is in tabular format. The funct
4 min read
Writing to Files in R Programming
R programming Language is one of the very powerful languages specially used for data analytics in various fields. Analysis of data means reading and writing data from various files like excel, CSV, text files, etc. Today we will be dealing with various ways of writing data to different types of files using R programming. R - Writing to Files Writin
2 min read
How to Write Multiple Excel Files From Column Values - R programming
A data frame is a cell-based structure comprising rows and columns belonging to the same or different data types. Each cell in the data frame is associated with a unique value, either a definite value or a missing value, indicated by NA. The data frame structure is in complete accordance with the Excel sheet structure. Therefore, the data frame val
6 min read
How to Convert XML to DataFrame in R?
A Data Frame is a two-dimensional and tabular data structure in the R that is similar to a table in the database or an Excel spreadsheet. It is one of the most commonly used data structures for the data analysis in R with the columns representing the various and rows representing the observations. XML(Extensible Markup Language)XML is the markup la
4 min read
How to Convert XML to CSV in R?
Converting data from XML to CSV format can be a handy skill, especially when you need to work with data in a more accessible format like CSV. Here, we'll discuss about the process of converting XML files to CSV using R programming language for data analysis. What is XML (eXtensible Markup Language)?XML is the markup language that can be defines the
4 min read
How to Extract Text from XML File Using R
A markup language that defines the set of rules for encoding documents in a format that is both human-readable and machine-readable. XML can be widely used to represent arbitrary data structures, such as those used in web services. Extracting XML (Extensible Markup Language) is a markup language that defines the rules for encoding documents in a hu
4 min read
How to Read XML File in R?
XML (Extensible Markup Language) can be a widely used format for storing and transporting data. It can be structured and allowing the both humans and machines to easily parse and interpret the data it contains. In R programming, reading and processing XML files is straightforward thanks to the various packages specifically designed for XML manipula
5 min read
What is the Relation Between R Programming and Hadoop Programming?
The relation between R programming and Hadoop revolves around integrating R with the Hadoop ecosystem to analyze large datasets that are stored in a Hadoop environment. R, primarily used for statistical analysis and data visualization, is not inherently built for handling big data. However, when combined with Hadoop, it can leverage Hadoop's distri
3 min read
Get and Set Working Directory in R
In this article, we are going to see how to get and set a working directory in R Programming Language. How to Get Working directory: getwd(): The getwd() method is used to gather information about the current working pathname or default working directory. This function has no arguments. It returns an absolute pathname. It returns NULL in case there
2 min read
Working With Different Versions of an R Package
R programming language offers different functionalities through different packages available in online repositories. The official repository CRAN keeps updating these packages and frequently publishes newer versions of packages. R's package system is set by default to overwrite the existing versions of packages so that the user always has the lates
8 min read
Working with Legends in R using ggplot2
A legend in a plot helps us to understand which groups belong to each bar, line, or box based on its type, color, etc. We can add a legend box in R using the legend() function. These work as guides. The keys can be determined by scale breaks. In this article, we will be working with legends and associated customization using ggplot2 in R programmin
7 min read
How to Fix in R: Cannot change working directory
In this article, we focus on how we can fix the "cannot change working directory" error in the R programming language. One error that one may encounter in R is: Error in setwd("C:/Bhuwanesh/gfg") : cannot change working directory Such an error occurs when we try to set a working directory in R, but a part of the file path is misspelled. When this e
2 min read
Working with databases and SQL in RStudio
In today’s data-driven world, the interface between SQL (Structured Query Language) and R has become a must-have for data professionals. SQL empowers us to efficiently interact with relational databases, while R programming language is versatile for data analysis. Combining these two powerful tools can dramatically increase your data conversion cap
9 min read
Working with Text in R
R Programming Language is used for statistical computing and is used by many data miners and statisticians for developing statistical software and data analysis. It includes machine learning algorithms, linear regression, time series, and statistical inference to name a few. R and its libraries implement a wide variety of statistical and graphical
6 min read
Working with Axes in R using ggplot2
The ggplot2 package is a powerful and widely used package for graphic visualization. It can be used to provide a lot of aesthetic mappings to the plotted graphs. This package is widely available in the R Programming Language. The package can be downloaded and installed into the working space using the following command. install.packages("ggplot2")T
7 min read
Working with R Scripts in Power BI Desktop
Power BI is a very useful tool when it comes to working with powerful scripting languages such as R Programming. Power BI in itself is a powerful tool for data visualization. Using R scripts in Power BI Desktop can further enhance your data analysis and visualization capabilities, making the job of data analysts much easier. Working with R Scripts
4 min read
Why Would you Learn R if you have Excel working well?
Answer: While Excel is a powerful tool for basic data analysis and visualization, learning R offers significant advantages for more complex, large-scale, and advanced statistical tasks. R is particularly valuable for handling larger datasets, automating repetitive tasks, performing sophisticated statistical analyses, and creating advanced data visu
3 min read
How to read column names and metadata from feather files in R arrow?
To access column names and metadata from feather files in R programming, we use the R Arrow package to load the feather file into a data frame. After loading the feather file, we can retrieve the column names and metadata attributes by using the Feather package. What is Arrow Package in R? The Arrow package available in R offers a range of tools to
3 min read
Save and Load RData Workspace Files in R
In this article, we will discuss how to save and load R data workspace files in R programming language. Method 1: Using save.image and load method The save.image method in R is used to save the current workspace files. It is an extended version of the save method in R which is used to create a list of all the declared data objects and save them int
3 min read
Writing to CSV files in R
For Data Analysis sometimes creating CSV data file is required and do some operations on it as per our requirement. So, In this article we are going to learn that how to write data to CSV File using R Programming Language. To write to csv file write.csv() function is used. Syntax: write.csv(data, path) Parameter: data: data to be added to csvpath:
1 min read
Article Tags :