Jun 24, 2016

JavaScript: XML to JSON Conversion


Sometimes in order to achieve our objectives as a developer, we need read some XML data in JavaScript, but as we know, XML is about a lot of plain text tags, that can be a nightmare to parse. So what if we convert it to the native JavaScript Object Notation (JSON) ? here you can see a very simple way !

The library used is called "x2js", you can get it from here. Let's start with a simple single-line example:

<html><meta charset="utf-8">
 <script src="xml2json.js" charset="UTF-8"></script>
 <script type="text/javascript">
  console.log((new X2JS()).xml_str2json("<RootTag>content</RootTag>"));
 </script>
</html> 

As you can see, just import the library and create a X2JS object type, then access its 'xml_str2json' method supplying the XML content as parameter, the functions then returns our JSON object, that represents the XML data. Here is the browser's console output:

Object { RootTag: "content" }

Now an improved example with XML namespaces and a list:

<html>
<meta charset="utf-8">
 <script src="xml2json.js" charset="UTF-8"></script>
 <script type="text/javascript">
  var xml = 
  "<RootTag xmlns:ns1='http://www.l3oc.com/namespace'>"+
  "<ns1:tag1>Success</ns1:tag1>"+
  "<list><item>item 1</item><item>item 2</item></list>"+
  "</RootTag>";
  
  console.log((new X2JS()).xml_str2json(xml));
 </script>
</html> 

The 'tag1' has a namespace and the tag 'list' two items, the browser's output with the object can be seen below:



Pay attention to the "__text" attribute, it contains the tags content, so to get it, you need access the parameter name like "RootTag.tag1.__text" to get the 'Success' text from the tag1. Well, that's all ! The library has no dependencies, supports JSON to XML conversion and has a lot of others features too, check them out!

About the versions
  • x2js 1.2.0
  • Firefox 44.0.2

0 comentários :

Post a Comment