Read and Display Server-Side XML with JavaScript Article

Share this article

XML is a very important base on which Web Services work, and, in conjunction with a number of client- and server-side languages, can be put to good effect.

Let’s see how we can use XML and client side JavaScript to display the contents of a XML file, access child elements, manipulate elements, and more!

Browser Issues

When it comes to client side languages, browser incompatibilities are a major issue. But here, using XML and JavaScript, it’s XML that’s the issue: not all browsers support the parsing of XML documents.

I’ll use IE6 to explain the codes. Browsers that don’t support XML can’t read these, so when you view an XML file in such a browser, it will simply ignore all the tags.

Sample XML File

Let’s consider a sample XML file, which shows employee data and Turnover of a company:

<?xml version="1.0" ?>  
<company>
<employee id="001" sex="M" age="19">Premshree Pillai</employee>
<employee id="002" sex="M" age="24">Kumar Singh</employee>
<employee id="003" sex="M" age="21">Ranjit Kapoor</employee>
<turnover>
<year id="2000">100,000</year>
<year id="2001">140,000</year>
<year id="2002">200,000</year>
</turnover>
</company>
Manipulating the XML file data using JavaScript

Load The XML File

You can load a XML fie from JavaScript like this:

var xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); 
function loadXML(xmlFile)
{
 xmlDoc.async="false";
 xmlDoc.onreadystatechange=verify;
 xmlDoc.load(xmlFile);
 xmlObj=xmlDoc.documentElement;
}

Actually, just the last two lines of the function are enough to load the XML file. The previous two lines ensure that any JavaScript functions that we may use to manipulate the XML file data later, will not perform any function on an uninitialized object. Thus the function verify()is called:

function verify() 
{
 // 0 Object is not initialized
 // 1 Loading object is loading data
 // 2 Loaded object has loaded data
 // 3 Data from object can be worked with
 // 4 Object completely initialized
 if (xmlDoc.readyState != 4)
 {
   return false;
 }
}

Now the XML file can be loaded:

loadXML('xml_file.xml');

Display The Contents of the XML File

View the entire contents of the XML file using alert(xmlObj.xml); The whole XML file will be displayed in an alert box as it is, with proper indentation.

Children and Nodes

In the above XML file, <company> is the top level tag under which all other tags fall. These tags are called children. This XML file can be represented graphically like a folder-tree:

989_folderimage

In the above XML file, the top level tag <company> has 4 children.

The numbering of children (as is usual in all languages) starts from 0 (zero). The <turnover> tag has 3 children under it.

We can find the number of children a tag has by using the childNodes.length property. Thus the number of children of <company> tag (here, 4) can be found by using xmlObj.childNodes.length

The number of children of <turnover> tag (here, 3) can be found by using xmlObj.childNodes(3).childNodes.length

Here we use childNodes(3) because <turnover> is the 3rd child of <company>

Test for Children

You can test whether a particular node child has any children using childNodes(i).hasChildNodes

Thus, xmlObj.childNodes(3).hasChildNodes() will return true. xmlObj.childNodes(2).hasChildNodes() will return false, as the <employee> tag doesn’t have any children.

Get Tag Name

You can get the tag name of a child using childNodes(i).tagName. Thus, xmlObj.tagName will return “company”. xmlObj.childNodes(0).tagName will return “employee”. xmlObj.childNodes(3).childNodes(0).tagName will return “year”.

Display the Content of a Tag

In the XML file, the content of the 1st <employee> tag is “Premshree Pillai”. You can get this value using xmlObj.childNodes(0).firstChild.text

xmlObj.childNodes(2).firstChild.text will return "Suhasini Pandita". Similarly, xmlObj.childNodes(3).childNodes(1).firstChild.text will return "140,000".

Attributes

In the XML file, the <employee> tag has 3 attributes. An attribute can be accessed using childNodes(i).getAttribute("AttributeName"). Thus, xmlObj.childNodes(0).getAttribute("id") will return “001”. xmlObj.childNodes(1).getAttribute("age") will return “24”. And xmlObj.childNodes(2).getAttribute("sex") will return “F”.

Go to page: 1 | 2

Frequently Asked Questions (FAQs) about Server-Side XML and JavaScript

How can I parse XML in JavaScript on the server-side?

Parsing XML in JavaScript on the server-side can be done using various libraries such as xml2js, fast-xml-parser, and xmldom. For instance, with xml2js, you first need to install it using npm install xml2js. Then, you can use it to parse XML data as follows:

var xml2js = require('xml2js');
var parser = new xml2js.Parser();
parser.parseString(xml, function (err, result) {
console.log(result);
});
In this code, ‘xml’ is the XML data you want to parse. The parseString function converts XML data into a JavaScript object.

How can I read an XML file in JavaScript?

Reading an XML file in JavaScript can be done using the FileReader API for client-side or the fs module for server-side. For server-side, you can use the fs module’s readFile function as follows:

var fs = require('fs');
fs.readFile('test.xml', 'utf8', function(err, data) {
if (err) throw err;
console.log(data);
});
In this code, ‘test.xml’ is the XML file you want to read. The readFile function reads the file and returns its content as a string.

How can I convert XML to JSON in JavaScript?

Converting XML to JSON in JavaScript can be done using libraries such as xml2js and fast-xml-parser. For instance, with xml2js, you can convert XML data to JSON as follows:

var xml2js = require('xml2js');
var parser = new xml2js.Parser();
parser.parseString(xml, function (err, result) {
console.log(JSON.stringify(result));
});
In this code, ‘xml’ is the XML data you want to convert. The parseString function converts XML data into a JavaScript object, and JSON.stringify converts the JavaScript object into a JSON string.

How can I handle XML namespaces in JavaScript?

Handling XML namespaces in JavaScript can be tricky because JavaScript doesn’t have built-in support for XML namespaces. However, you can use libraries such as xmldom and xpath to handle XML namespaces. For instance, with xmldom and xpath, you can select elements in a namespace as follows:

var DOMParser = require('xmldom').DOMParser;
var xpath = require('xpath');
var doc = new DOMParser().parseFromString(xml);
var select = xpath.useNamespaces({"ns": "http://www.example.com"});
var nodes = select("//ns:element", doc);
In this code, ‘xml’ is the XML data, ‘http://www.example.com‘ is the namespace URI, and ‘element’ is the element you want to select. The useNamespaces function creates a namespace-resolver function, and the second function selects elements in the namespace.

How can I validate XML against an XSD in JavaScript?

Validating XML against an XSD in JavaScript can be done using libraries such as libxmljs. However, please note that JavaScript doesn’t have robust support for XML Schema validation compared to languages like Java and C#. Therefore, you might need to use a workaround such as calling a Java or C# program from your JavaScript code or using a web service for XML Schema validation.

How can I transform XML using XSLT in JavaScript?

Transforming XML using XSLT in JavaScript can be done using libraries such as xslt4node. However, please note that JavaScript doesn’t have robust support for XSLT compared to languages like Java and C#. Therefore, you might need to use a workaround such as calling a Java or C# program from your JavaScript code or using a web service for XSLT transformation.

How can I create XML in JavaScript?

Creating XML in JavaScript can be done using the DOM API for client-side or libraries such as xmlbuilder for server-side. For instance, with xmlbuilder, you can create XML data as follows:

var builder = require('xmlbuilder');
var xml = builder.create('root')
.ele('element', 'content')
.end({ pretty: true});
console.log(xml);
In this code, ‘root’ is the root element, ‘element’ is a child element, and ‘content’ is the content of the child element. The create function creates a new XML document, the ele function adds an element, and the end function finalizes the XML document.

How can I serialize XML in JavaScript?

Serializing XML in JavaScript can be done using the XMLSerializer API for client-side or libraries such as xmlbuilder for server-side. For instance, with xmlbuilder, you can serialize XML data as follows:

var builder = require('xmlbuilder');
var xml = builder.create('root').end({ pretty: true});
console.log(xml);
In this code, ‘root’ is the root element. The create function creates a new XML document, and the end function finalizes and serializes the XML document.

How can I use XPath in JavaScript?

Using XPath in JavaScript can be done using the DOM API for client-side or libraries such as xpath for server-side. For instance, with xpath, you can select elements using XPath as follows:

var xpath = require('xpath');
var nodes = xpath.select("//element", doc);
In this code, ‘doc’ is the XML document, and ‘element’ is the element you want to select. The select function selects elements using XPath.

How can I handle XML errors in JavaScript?

Handling XML errors in JavaScript can be done using try-catch blocks and error callbacks. For instance, with xml2js, you can handle parsing errors as follows:

var xml2js = require('xml2js');
var parser = new xml2js.Parser();
parser.parseString(xml, function (err, result) {
if (err) {
console.error("Error parsing XML: " + err);
} else {
console.log(result);
}
});
In this code, ‘xml’ is the XML data you want to parse. The parseString function converts XML data into a JavaScript object and calls the callback function with an error argument if there’s an error.

Premshree PillaiPremshree Pillai
View Author

Premshree studies engineering in Information Technology at Mumbai University, India. He's written articles for a range of popular Indian IT magazines, and his site, QikSearch has featured in 'Digit' Magazine - India's No. 1 technology magazine.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week