DOMParser Example

Parsing xml with javascript

Many web services provide data in XML format. Luckily all modern browsers have a built-in XML parser and tools to parse and select tags in XML documents. The XML parser converts an XML document into an XML DOM object — which can then be manipulated with JavaScript using the same vocabulary as HTML.

Some useful javascript methods and properties

Properties
  • childNodes — The childNodes property returns a NodeList of child nodes for the document.
  • nodeValue — The nodeValue property sets or returns the value of a node, depending on its type.
  • textContent — The textContent property sets or returns the textual content of a node and its descendants. On setting, any child nodes are removed and replaced by a single Text node containing the string this property is set to.
Methods

The methods querySelector and querySelectorAll allow to select elements by CSS 3 query. The querySelector returns only first element (in tree depth-first walking order), the querySelectorAll gets all of them.

Читайте также:  Рамка вокруг таблицы
Ojbects
  • DOMParser — Provides methods to build XMLDocument objects from XML formatted strings or streams.
  • ActiveXObject — The ActiveXObject object is used to create instances of OLE Automation objects in Internet Explorer on Windows operating systems. You can use the methods and properties supported by Automation objects in JavaScript. ActiveXObject object is only supported by Internet Explorer.
var myOrders = "" + "" + "" + "" + "12345" + "" + "" + "" + "ABC" + "2" + "" + "" + "DEF" + "4" + "" + "" + "" + "" + "" + "12346" + "" + "" + "" + "HIJ" + "1" + "" + "" + "KLM" + "2" + "" + "" + "" +""; if (window.DOMParser) < parser=new DOMParser(); xmlDoc=parser.parseFromString(myOrders,"text/xml"); >else // Internet Explorer < xmlDoc=new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async=false; xmlDoc.loadXML(myOrders); >var myValue ="";

1. Get value of first order number

document.write("
1. Get value of first order number
"); var myValue = xmlDoc.getElementsByTagName("OrderNo")[0].childNodes[0].nodeValue; document.write(myValue + "

");

2. Get value of first sku number in first order

document.write("
2. get value of first sku number in first order
"); myValue = xmlDoc.getElementsByTagName("Sku")[0].childNodes[0].nodeValue; document.write(myValue + "

");

3. list SKUs ordered

document.write("
3. List all SKUs ordered
"); myValue = xmlDoc.getElementsByTagName("Sku"); // list all all SKUs ordered for(i = 0; i < myValue.length; i++)< var node = myValue[i].firstChild.nodeValue; document.write(node + "
"); >

4. Get all Orders Numbers and SKU Ordered for each Order using querySelector and querySelectorAll

document.write("
4. Get all Orders Numbers and SKU Ordered for each Order
"); myOrders= xmlDoc.getElementsByTagName("Order"); // iterate through orders for(x = 0; x < myOrders.length; x++)< var myOrder = myOrders[x].querySelector('OrderNo').textContent; document.write(myOrder + "
"); // iterate through SKUS in each order var mySkus = myOrders[x].querySelectorAll('OrderDetail > Sku'); for(y = 0; y < mySkus.length; y++)< document.write("-- SKU: " + mySkus[y].firstChild.nodeValue + "
"); > > document.write("
");
12345 -- SKU: ABC -- SKU: DEF 12346 -- SKU: HIJ -- SKU: KLM

5. Using jQuery parseXML and .find

Источник

Parsing and serializing XML

At times, you may need to parse XML content and convert it into a DOM tree, or, conversely, serialize an existing DOM tree into XML. In this article, we’ll look at the objects provided by the web platform to make the common tasks of serializing and parsing XML easy.

Читайте также:  Css плавное увеличение шрифта при наведении

Serializes DOM trees, converting them into strings containing XML.

Constructs a DOM tree by parsing a string containing XML, returning a XMLDocument or Document as appropriate based on the input data.

Loads content from a URL; XML content is returned as an XML Document object with a DOM tree built from the XML itself.

A technology for creating strings that contain addresses for specific portions of an XML document, and locating XML nodes based on those addresses.

Creating an XML document

Using one of the following approaches to create an XML document (which is an instance of Document ).

Parsing strings into DOM trees

This example converts an XML fragment in a string into a DOM tree using a DOMParser :

const xmlStr = 'hey!'; const parser = new DOMParser(); const doc = parser.parseFromString(xmlStr, "application/xml"); // print the name of the root element or error message const errorNode = doc.querySelector("parsererror"); if (errorNode)  console.log("error while parsing"); > else  console.log(doc.documentElement.nodeName); > 

Parsing URL-addressable resources into DOM trees

Using XMLHttpRequest

Here is sample code that reads and parses a URL-addressable XML file into a DOM tree:

const xhr = new XMLHttpRequest(); xhr.onload = () =>  dump(xhr.responseXML.documentElement.nodeName); >; xhr.onerror = () =>  dump("Error while getting XML."); >; xhr.open("GET", "example.xml"); xhr.responseType = "document"; xhr.send(); 

The value in the xhr object’s responseXML field is a Document constructed by parsing the XML.

If the document is HTML, the code shown above will return a Document . If the document is XML, the resulting object is actually a XMLDocument . The two types are essentially the same; the difference is largely historical, although differentiating has some practical benefits as well.

Note: There is in fact an HTMLDocument interface as well, but it is not necessarily an independent type. In some browsers it is, while in others it is an alias for the Document interface.

Serializing an XML document

Given a Document , you can serialize the document’s DOM tree back into XML using the XMLSerializer.serializeToString() method.

Use the following approaches to serialize the contents of the XML document you created in the previous section.

Serializing DOM trees to strings

First, create a DOM tree as described in How to Create a DOM tree. Alternatively, use a DOM tree obtained from XMLHttpRequest .

To serialize the DOM tree doc into XML text, call XMLSerializer.serializeToString() :

const serializer = new XMLSerializer(); const xmlStr = serializer.serializeToString(doc); 

Serializing HTML documents

If the DOM you have is an HTML document, you can serialize using serializeToString() , but there is a simpler option: just use the Element.innerHTML property (if you want just the descendants of the specified node) or the Element.outerHTML property if you want the node and all its descendants.

const docInnerHtml = document.documentElement.innerHTML; 

As a result, docInnerHtml is a string containing the HTML of the contents of the document; that is, the element’s contents.

You can get HTML corresponding to the and its descendants with this code:

const docOuterHtml = document.documentElement.outerHTML; 

See also

Found a content problem with this page?

This page was last modified on Jul 4, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Parsing XML in Javascript with DOMParser

Follow us on our fanpages to receive notifications every time there are new articles. Facebook Twitter

1- DOMParser

The DOMParser is an interface provides the ability to parse XML or HTML source code from a String into a DOM Document.

 // Create a DOMParser var parser = new DOMParser(); 

 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 tag.

 . (error description) (a snippet of the source XML)  . 

You should write a utility function to parse XML. This function throw errors if XML is unvalid.

 // 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 : 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

Reset

 // 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 : 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 = "" + " " + " " + " Putin " + " putin " + " 95 " + " " + " " + " Trump " + " trump " + " 90 " + " " + " " + " Kim " + " kim " + " 85 " + " " + " "; 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.  var rootElement = doc.documentElement; // var children = rootElement.childNodes; for(var i =0; i < children.length; i++) < var child = children[i]; // 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)

View more Tutorials:

These are online courses outside the o7planning website that we introduced, which may include free or discounted courses.

  • The Complete JavaScript Bootcamp
  • Getting really good at JavaScript and TypeScript
  • Essentials of JavaScript Practice Coding Exercises Tips
  • JavaScript For Beginners — Learn JavaScript From Scratch
  • Learn JavaScript From Scratch:Become Top Rated Web Developer
  • Javascript for Beginners
  • Learning ECMAScript 6: Moving to the New JavaScript
  • JavaScript Dynamic Quiz Application from Scratch JSON AJAX
  • JavaScript Intro to learning JavaScript web programming
  • Byte-Sized-Chunks: Dynamic Prototypes in Javascript
  • Learn ECMAScript 2015 — ES6 Best Course
  • Getting started with javascript and its core concepts
  • Learn JavaScript Fundamentals
  • * * Master ECMAScript 2015 (ES6)
  • Quick JavaScript Core learning Course JavaScript Essentials
  • HTML CSS JavaScript: Most popular ways to code HTML CSS JS
  • * * Start 3D GIS Web Development in JavaScript
  • Learning JavaScript Programming Tutorial. A Definitive Guide
  • 2D Game Development With HTML5 Canvas, JS — Tic Tac Toe Game
  • JavaScript for Beginning Web Developers
  • The Web Development Course: HTML5, CSS3, JavaScript
  • JavaScript in 55 Minutes
  • JavaScript in Action JavaScript Projects
  • The complete beginner JavaScript ES5, ES6 and JQuery Course
  • * * Introductory To JavaScript — Learn The Basics of JavaScript

Источник

Оцените статью