Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

How to Display XML Data In React

Jun 24, 2020 • 5 Minute Read

Introduction

React is a popular JavaScript library used to flawlessly create dynamic and reusable user interface elements. XML is the oldest file format generally used to manage database data and share over the internet, since it isan option for getting responses and sending requests to the server.

In this guide, you will learn how to consume XML data from the server and render it into a React app.

Fetching XML Data from the Server

React does not have an inbuilt mechanism to fetch and display data, but there are tons of XML parsing libraries available to use for this. Before beginning the React app guide, you must have XML data to show, which you may need to collect from the server.

To fetch the data from the server, use the HttpClient Axios, whichis installed using the below npm command.

      npm install axios
    

Now that you have installed Axios, create a new component, for example, ParseXml.jsx, and implement the componentDidMount() lifecycle hook as shown below.

      componentDidMount() {
	var self = this;
	axios
	.get("https://fakerestapi.azurewebsites.net/api/Authors", {
		"Content-Type": "application/xml; charset=utf-8"
	 })
	.then(function(response) {
		self.setState({ authors: response.data });
	})
	.catch(function(error) {
		console.log(error);
	});
}
    

In the above lines of code, the fake RestAPI gets the XML data from the this URL.

      https://fakerestapi.azurewebsites.net/api/Authors
    

You can use any API data that you want; this example is simply for this guide..

After getting the response from the server, the data needs to be stored somewhere in the component, and the local state is a primary choice.

      .then(function(response) {
    self.setState({ authors: response.data });
})
    

You can observe that the response comes from the server and stores data in a state variable called authors that can then be used to show the data to the end-user.

Showing XML Data in a React App

So far in this guide, you have used an HttpClient to fetch XML data from the server. The next step is to show the XML parsed data to the customer in various ways.

Using Content Type as XML

When fetching the data from the server, specify the content type as XML.

      axios
.get("https://fakerestapi.azurewebsites.net/api/Authors", {
	"Content-Type": "application/xml; charset=utf-8"
})
    

So, once you trigger the API, the response is parsed into the object, makong it easy to use and manipulate the object data.

      render() {
	const { authors } = this.state;
 
	return (
		<div>
			Parse XML using ReactJs
			{(authors && authors.length > 0) &&
			authors.map((item) => {
				return (
					<span>{item.FirstName}</span>
				)
			})
		}
		</div>
	);
}
    

In the above example with the state value authors, you can get the list of authors coming from the server. Using the .map() function helps you to iterate over the array items.

Using a Third-party XML Parsing Library

You have learned how to fetch XML data using an API and display it to the user. Alternatively, you can use various third-party libraries, some of which include:

  • xml-to-react
  • xml2js
  • xml-to-json
  • xml-js
  • react-xml-parser

These are few of the libraries that can be used to parse XML data in a React app. Let’s try one of them.

Before using the library, you need to install it. I'll demonstrate the xml2js library in this guide.

      npm install xml2js
    

After installing the library, implement the library functionality.

      render() {
	let parser = new xml2js.Parser();
 	parser.parseString(
		`<email>
		<to>Test</to>
		<from>Test1</from>
		<heading>Test email</heading>
		<body>Email regards to xml data parsing in React</body>
		</email>`,
		function(err, result) {
			 console.log(result);
		}
	);
	return <div>Parse XML using ReactJs</div>;
}
    

As you can observe in the above example, the parser used is xml2jsParser(), which initializes the parser function from the library.

After initializing the parser, the next step is to provide the XML data to the parser using the function parseString(), which accepts the valid XML data.

Once you execute the above example, the console log should look as shown below.

The XML data is wholly converted into a JavaScript object, and each child of the XML is the sub-child of the parent object, as you can see in the screenshot.

This is how the XML data from an internal or external source can be parsed into an object or JSON using third-party libraries.

Conclusion

React is a JavaScript library, and everything in JavaScript is an object, but you may sometimes need to access various formats such as XML and JSON, so it's pretty easy to parse an object.

In this guide, you have learned how to parse XML data and show it to the user by using a content type of the response and a third-party library. I hope it's helpful to you!

Gaurav Singhal

Gaurav S.

Guarav is a Data Scientist with a strong background in computer science and mathematics. He has extensive research experience in data structures, statistical data analysis, and mathematical modeling. With a solid background in Web development he works with Python, JAVA, Django, HTML, Struts, Hibernate, Vaadin, Web Scrapping, Angular, and React. His data science skills include Python, Matplotlib, Tensorflows, Pandas, Numpy, Keras, CNN, ANN, NLP, Recommenders, Predictive analysis. He has built systems that have used both basic machine learning algorithms and complex deep neural network. He has worked in many data science projects, some of them are product recommendation, user sentiments, twitter bots, information retrieval, predictive analysis, data mining, image segmentation, SVMs, RandomForest etc.

More about this author