I am looking for a JavaScript library that parses an XML string and converts it to a JavaScript object. What are some good ones?
With a few lines of JavaScript code, you can read an XML file and update the data content of any HTML page.
To convert XML text to JavaScript object, use xml2js() . To convert XML text to JSON text, use xml2json() .
XML parser is a software library or a package that provides interface for client applications to work with XML documents. It checks for proper format of the XML document and may also validate the XML documents. Modern day browsers have built-in XML parsers. The goal of a parser is to transform XML into a readable code.
Following are the various types of parsers which are commonly used to parse XML documents. Dom Parser − Parses an XML document by loading the complete contents of the document and creating its complete hierarchical tree in memory. SAX Parser − Parses an XML document on event-based triggers.
The following function parses XML and returns a JavaScript object with a scheme that corresponds to the XML. XML siblings w/ the same name are collapsed into arrays. nodes with names that can be found in the arrayTags
parameter (array of tag name strings) always yield arrays even in case of only one tag occurrence. arrayTags
can be omitted. Text nodes with only spaces are discarded.
function parseXml(xml, arrayTags) { let dom = null; if (window.DOMParser) dom = (new DOMParser()).parseFromString(xml, "text/xml"); else if (window.ActiveXObject) { dom = new ActiveXObject('Microsoft.XMLDOM'); dom.async = false; if (!dom.loadXML(xml)) throw dom.parseError.reason + " " + dom.parseError.srcText; } else throw new Error("cannot parse xml string!"); function parseNode(xmlNode, result) { if (xmlNode.nodeName == "#text") { let v = xmlNode.nodeValue; if (v.trim()) result['#text'] = v; return; } let jsonNode = {}, existing = result[xmlNode.nodeName]; if (existing) { if (!Array.isArray(existing)) result[xmlNode.nodeName] = [existing, jsonNode]; else result[xmlNode.nodeName].push(jsonNode); } else { if (arrayTags && arrayTags.indexOf(xmlNode.nodeName) != -1) result[xmlNode.nodeName] = [jsonNode]; else result[xmlNode.nodeName] = jsonNode; } if (xmlNode.attributes) for (let attribute of xmlNode.attributes) jsonNode[attribute.nodeName] = attribute.nodeValue; for (let node of xmlNode.childNodes) parseNode(node, jsonNode); } let result = {}; for (let node of dom.childNodes) parseNode(node, result); return result; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With