Parsing XML in Javascript with DOMParser
1. DOMParser
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
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;
}
-
See also:
ECMAScript, Javascript Tutorials
- Introduction to Javascript and ECMAScript
- Quickstart with Javascript
- Alert, Confirm, Prompt Dialog Box in Javascript
- Quickstart with JavaScript
- JavaScript Variables Tutorial with Examples
- Bitwise Operations
- JavaScript Arrays Tutorial with Examples
- JavaScript Loops Tutorial with Examples
- JavaScript Functions Tutorial with Examples
- JavaScript Number Tutorial with Examples
- JavaScript Boolean Tutorial with Examples
- JavaScript Strings Tutorial with Examples
- JavaScript if else Statement Tutorial with Examples
- JavaScript Switch Statement
- JavaScript Error Handling Tutorial with Examples
- JavaScript Date Tutorial with Examples
- JavaScript Modules Tutorial with Examples
- The History of Modules in JavaScript
- JavaScript setTimeout and setInterval Function
- Javascript Form Validation Tutorial with Examples
- JavaScript Web Cookies Tutorial with Examples
- JavaScript void Keyword Tutorial with Examples
- Classes and Objects in JavaScript
- Class and inheritance simulation techniques in JavaScript
- Inheritance and polymorphism in JavaScript
- Undertanding Duck Typing in JavaScript
- JavaScript Symbols Tutorial with Examples
- JavaScript Set Collection Tutorial with Examples
- JavaScript Map Collection Tutorial with Examples
- Undertanding JavaScript Iterables and Iterators
- JavaScript Regular Expressions Tutorial with Examples
- JavaScript Promise, Async/Await Tutorial with Examples
- Javascript Window Tutorial with Examples
- Javascript Console Tutorial with Examples
- Javascript Screen Tutorial with Examples
- Javascript Navigator Tutorial with Examples
- Javascript Geolocation API Tutorial with Examples
- Javascript Location Tutorial with Examples
- Javascript History API Tutorial with Examples
- Javascript Statusbar Tutorial with Examples
- Javascript Locationbar Tutorial with Examples
- Javascript Scrollbars Tutorial with Examples
- Javascript Menubar Tutorial with Examples
- JavaScript JSON Tutorial with Examples
- JavaScript Event Handling Tutorial with Examples
- Javascript MouseEvent Tutorial with Examples
- Javascript WheelEvent Tutorial with Examples
- Javascript KeyboardEvent Tutorial with Examples
- Javascript FocusEvent Tutorial with Examples
- Javascript InputEvent Tutorial with Examples
- Javascript ChangeEvent Tutorial with Examples
- Javascript DragEvent Tutorial with Examples
- Javascript HashChangeEvent Tutorial with Examples
- Javascript URL Encoding Tutorial with Examples
- Javascript FileReader Tutorial with Examples
- Javascript XMLHttpRequest Tutorial with Examples
- Javascript Fetch API Tutorial with Examples
- Parsing XML in Javascript with DOMParser
- Introduction to Javascript HTML5 Canvas API
- Highlighting code with SyntaxHighlighter Javascript library
- What are polyfills in programming science?
Show More