jquery xml to json – The XML to JSON Plugin (jQuery.xml2json) is a script you can use to convert simple XML into a JSON object.
jquery xml to json
Convert the XML data you provide into JSON data. XML has to be parsed with an XML parser. JSON can be parsed by a standard JavaScript function.
Convert XML to JSON (and back) using Javascript
function xml2json(xml) { try { var obj = {}; if (xml.children.length > 0) { for (var i = 0; i < xml.children.length; i++) { var item = xml.children.item(i); var nodeName = item.nodeName; if (typeof (obj[nodeName]) == "undefined") { obj[nodeName] = xml2json(item); } else { if (typeof (obj[nodeName].push) == "undefined") { var old = obj[nodeName]; obj[nodeName] = []; obj[nodeName].push(old); } obj[nodeName].push(xml2json(item)); } } } else { obj = xml.textContent; } return obj; } catch (e) { console.log(e.message); } }
Example 2: jquery xml to json
const xmlSample = 'tag content another content '; console.log(parseXmlToJson(xmlSample)); function parseXmlToJson(xml) { const json = {}; for (const res of xml.matchAll(/(?:<(\w*)(?:\s[^>]*)*>)((?:(?!<\1).)*)(?:<\/\1>)|<(\w*)(?:\s*)*\/>/gm)) { const key = res[1] || res[3]; const value = res[2] && parseXmlToJson(res[2]); json[key] = ((value && Object.keys(value).length) ? value : res[2]) || null; } return json; } inside content
Click Here: Demo
Convert XML to JSON with JavaScript
// Changes XML to JSON function xmlToJson(xml) { // Create the return object var obj = {}; if (xml.nodeType == 1) { // element // do attributes if (xml.attributes.length > 0) { obj["@attributes"] = {}; for (var j = 0; j < xml.attributes.length; j++) { var attribute = xml.attributes.item(j); obj["@attributes"][attribute.nodeName] = attribute.nodeValue; } } } else if (xml.nodeType == 3) { // text obj = xml.nodeValue; } // do children if (xml.hasChildNodes()) { for(var i = 0; i < xml.childNodes.length; i++) { var item = xml.childNodes.item(i); var nodeName = item.nodeName; if (typeof(obj[nodeName]) == "undefined") { obj[nodeName] = xmlToJson(item); } else { if (typeof(obj[nodeName].push) == "undefined") { var old = obj[nodeName]; obj[nodeName] = []; obj[nodeName].push(old); } obj[nodeName].push(xmlToJson(item)); } } } return obj; };
Don't Miss : Convert XML To JSON In PHP
I hope you get an idea about jquery xml to json.
I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this Article are always welcome.
If you enjoyed and liked this post, don’t forget to share.