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