Introduction:
A straightforward text-based format called Extensible Markup Language (XML) is used to describe structured data, including documents, data, configuration, books, transactions, invoices, and much more. In order to make it more suited for usage on the Web, it was adapted from an earlier standard format called SGML (ISO 8879).
One of the most popular formats for exchanging structured data today is XML, which is utilized locally as well as through networks by people, programs, and computers.
In this article, we will convert the XML files to JSON format.
Get Started:
Step 1: Set up your Angular project.
After selecting the folder where you wish to launch your Angular project, type the following command into a terminal or command window.
ng new xml-to-json
Install the following dependencies after creating the project.
Add xml2js…
npm install xml2js
Add timers…
npm install timers
Step 2: Add the file upload tag in your app.component.html
<input type="file" accept="text/xml" (change)="onUploadXML($event)">
Step 3: Add the following code to your app.component.ts file
import the xml2js in your component.
import * as xml2js from 'xml2js';
Add the onUploadXML() method…
onUploadXML(event: any) { let self = this; var file = event.target.files[0]; var textType = /text.*/; if (file.type.match(textType)) { var reader = new FileReader(); reader.onload = (function (e) { self.convert(reader.result); }) reader.readAsText(file); } else { alert("File not supported!"); } }
then add the convert() method for parsing the XML.
convert(xmlText: any) { xml2js.parseString(xmlText, function (err, result) { console.dir(result); }); }
Finally, save your code, run the application, go to your browser and upload the XML file. We stored the data in the console.dir(). So open the console and check it.