mydomain
No ADS
No ADS

Parsing XML in Javascript with DOMParser

  1. DOMParser
  2. Example with DOMParser

1. DOMParser

No ADS
The DOMParser is an interface provides the ability to parse XML or HTML source code from a String into a DOM Document.
Constructor:
// Create a DOMParser


var parser = new DOMParser();
Parse the XML/HTML source into a DOM Document:
var parser = new DOMParser();

// XMLDocument object:
var doc1 = parser.parseFromString(xmlString, "text/xml");


// Document object:
var doc2 = parser.parseFromString(xmlString, "text/html");
DOMParser can not parse XML source if this source is not valid but it doesn't fire an error. Instead, it returns a Document object containing faulty information. And this Document object has slightly different contents with different browsers, but always contains a <parsererror> tag.
...
<parsererror xmlns="http://www.mozilla.org/newlayout/xml/parsererror.xml">

   (error description)

   <sourcetext>(a snippet of the source XML)</sourcetext>

</parsererror>
...
You should write a utility function to parse XML. This function throw errors if XML is unvalid.
Utility Function
// Utility function:
// Return XMLDocument, or throw an Error!
function parseXML(xmlString) {
    var parser = new DOMParser();
    // Parse a simple Invalid XML source to get namespace of <parsererror>:
    var docError = parser.parseFromString('INVALID', 'text/xml');
    var parsererrorNS = docError.getElementsByTagName("parsererror")[0].namespaceURI;
    // Parse xmlString:
    // (XMLDocument object)
    var doc = parser.parseFromString(xmlString, 'text/xml');
    if (doc.getElementsByTagNameNS(parsererrorNS, 'parsererror').length > 0) {
        throw new Error('Error parsing XML');
    }
    return doc;
}
Note: By using XMLHttpRequest to read a XML data source from an URL, you can receive a XMLDocument object.

2. Example with DOMParser

No ADS
DOMParser will parse a XML into a DOM tree (like the following illustration). You need to use the APIs provided by DOM model to take necessary data.
domparser-example.html
<!DOCTYPE html>
<html>

<head>
    <title>DOMParser Example</title>
    <meta charset="UTF-8">

    <script src="domparser-example.js"></script>

</head>

<body>

    <h3>DOMParser example</h3>
    <a href="">Reset</a> <br><br>

    <button onclick = "clickHandler(event)">Click Me</button>
    <br><br>

    <textarea id="textarea-log" rows="15" style="width:100%;"></textarea>

</body>

</html>
domparser-example.js
// Utility function:
// Return XMLDocument, or throw an Error!
function parseXML(xmlString) {
    var parser = new DOMParser();
    // Parse a simple Invalid XML source to get namespace of <parsererror>:
    var docError = parser.parseFromString('INVALID', 'text/xml');
    var parsererrorNS = docError.getElementsByTagName("parsererror")[0].namespaceURI;
    // Parse xmlString:
    // (XMLDocument object)
    var doc = parser.parseFromString(xmlString, 'text/xml');
    if (doc.getElementsByTagNameNS(parsererrorNS, 'parsererror').length > 0) {
        throw new Error('Error parsing XML');
    }
    return doc;
}

// XML String:
var xmlString = "<?xml version = '1.0'?>" +
    "<class> " +
    "   <student rollNo = '393'> " +
    "      <fullName>Putin</fullName> " +
    "      <nickName>putin</nickName> " +
    "      <marks>95</marks> " +
    "   </student> "

    +
    "   <student rollNo = '493'> " +
    "      <fullName>Trump</fullName> " +
    "      <nickName>trump</nickName> " +
    "      <marks>90</marks> " +
    "   </student> "

    +
    "   <student rollNo = '593'> " +
    "      <fullName>Kim</fullName> " +
    "      <nickName>kim</nickName> " +
    "      <marks>85</marks> " +
    "   </student> " +
    "</class> ";


function clickHandler(evt) {

    console.log(xmlString);
    var doc;

    try {
        // XMLDocument object:
        doc = parseXML(xmlString);
        console.log(doc.documentElement);
    } catch (e) {
        alert(e);
        return;
    }
    resetLog();

    // Element object. <--> <class>
    var rootElement = doc.documentElement;
    //
    var children = rootElement.childNodes;

    for(var i =0; i< children.length; i++) {
       var child = children[i];
       // <studen> Element
       if(child.nodeType == Node.ELEMENT_NODE)  {
           var rollNo = child.getAttribute("rollNo");
           var fullNameElement = child.getElementsByTagName("fullName")[0];
           var nickNameElement = child.getElementsByTagName("nickName")[0];
           var marksElement = child.getElementsByTagName("marks")[0];

           var fullName = fullNameElement.textContent;
           var nickName = nickNameElement.textContent;
           var marks = marksElement.textContent;

           appendLog("rollNo: " + rollNo);
           appendLog("fullName: " + fullName);
           appendLog("nickName: " + nickName);
           appendLog("marks: " + marks);
       }
    }

}


function resetLog() {
    document.getElementById('textarea-log').value = "";
}

function appendLog(msg) {
    document.getElementById('textarea-log').value += "\n" + msg;
}
-
No ADS

ECMAScript, Javascript Tutorials

Show More
No ADS