Author avatar

Gaurav Singhal

How to Display XML Data In React

Gaurav Singhal

  • Jun 24, 2020
  • 5 Min read
  • 3,424 Views
  • Jun 24, 2020
  • 5 Min read
  • 3,424 Views
Web Development
Front End Web Development
Client-side Framework
React

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.

1
npm install axios 
powershell

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

1
2
3
4
5
6
7
8
9
10
11
12
13
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);
	});
}
jsx

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

1
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.

1
2
3
.then(function(response) {
    self.setState({ authors: response.data });
})
jsx

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.

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
render() {
	const { authors } = this.state;
 
	return (
		<div>
			Parse XML using ReactJs
			{(authors && authors.length > 0) &&
			authors.map((item) => {
				return (
					<span>{item.FirstName}</span>
				)
			})
		}
		</div>
	);
}
jsx

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.

1
npm install xml2js
powershell

After installing the library, implement the library functionality.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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>;
}
jsx

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.

Parsed XML data

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!

7