Non-jQuery version:
var parseXml;
if (window.DOMParser) {
parseXml = function(xmlStr) {
return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
};
} else if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) {
parseXml = function(xmlStr) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
};
} else {
parseXml = function() { return null; }
}
var xmlDoc = parseXml("<foo>Stuff</foo>");
if (xmlDoc) {
window.alert(xmlDoc.documentElement.nodeName);
}
Since jQuery 1.5, you can use jQuery.parseXML(), which works in exactly the same way as the above code:
var xmlDoc = jQuery.parseXML("<foo>Stuff</foo>");
if (xmlDoc) {
window.alert(xmlDoc.documentElement.nodeName);
}
Answer from Tim Down on Stack OverflowVideos
Can I convert JavaScript to XML automatically?
Should I rewrite from scratch or use a converter for JavaScript to XML?
What JavaScript features don't have a direct XML equivalent?
ยป npm install xml-js
Non-jQuery version:
var parseXml;
if (window.DOMParser) {
parseXml = function(xmlStr) {
return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
};
} else if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) {
parseXml = function(xmlStr) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
};
} else {
parseXml = function() { return null; }
}
var xmlDoc = parseXml("<foo>Stuff</foo>");
if (xmlDoc) {
window.alert(xmlDoc.documentElement.nodeName);
}
Since jQuery 1.5, you can use jQuery.parseXML(), which works in exactly the same way as the above code:
var xmlDoc = jQuery.parseXML("<foo>Stuff</foo>");
if (xmlDoc) {
window.alert(xmlDoc.documentElement.nodeName);
}
With jquery, you can use $.parseXML(str), https://api.jquery.com/jQuery.parseXML/
ยป npm install to-xml
replace your OBJtoXML function with
function OBJtoXML(obj) {
var xml = '';
for (var prop in obj) {
xml += obj[prop] instanceof Array ? '' : "<" + prop + ">";
if (obj[prop] instanceof Array) {
for (var array in obj[prop]) {
xml += "<" + prop + ">";
xml += OBJtoXML(new Object(obj[prop][array]));
xml += "</" + prop + ">";
}
} else if (typeof obj[prop] == "object") {
xml += OBJtoXML(new Object(obj[prop]));
} else {
xml += obj[prop];
}
xml += obj[prop] instanceof Array ? '' : "</" + prop + ">";
}
var xml = xml.replace(/<\/?[0-9]{1,}>/g, '');
return xml
}
Using xml-js lib
import { json2xml } from "xml-js";
const input = {
contact: {
name: `John & cia "example"`
}
};
const xml = json2xml(input, {
compact: true
});
// <contact><name>John & cia \"example\"</name></contact>
https://codesandbox.io/s/xml-json-forked-zgit4?file=/src/index.js:97-103
:)
I think this is the best one: Converting between XML and JSON
Be sure to read the accompanying article on the xml.com O'Reilly site, which goes into details of the problems with these conversions, which I think you will find enlightening. The fact that O'Reilly is hosting the article should indicate that Stefan's solution has merit.
https://github.com/abdmob/x2js - my own library (updated URL from http://code.google.com/p/x2js/):
This library provides XML to JSON (JavaScript Objects) and vice versa javascript conversion functions. The library is very small and doesn't require any other additional libraries.
API functions
- new X2JS() - to create your instance to access all library functionality. Also you could specify optional configuration options here
- X2JS.xml2json - Convert XML specified as DOM Object to JSON
- X2JS.json2xml - Convert JSON to XML DOM Object
- X2JS.xml_str2json - Convert XML specified as string to JSON
- X2JS.json2xml_str - Convert JSON to XML string
Online Demo on http://jsfiddle.net/abdmob/gkxucxrj/1/
var x2js = new X2JS();
function convertXml2JSon() {
$("#jsonArea").val(JSON.stringify(x2js.xml_str2json($("#xmlArea").val())));
}
function convertJSon2XML() {
$("#xmlArea").val(x2js.json2xml_str($.parseJSON($("#jsonArea").val())));
}
convertXml2JSon();
convertJSon2XML();
$("#convertToJsonBtn").click(convertXml2JSon);
$("#convertToXmlBtn").click(convertJSon2XML);
There is a non-standard API object: XMLSerializer (it is not standard though is implemented in all but IE browsers).
Its serializeToString method expects DOMNode object to be passed.
var sXML = new XMLSerializer().serializeToString(document.body);
In Internet Explorer there is no way to retrieve proper XML for HTML, unless getting .outerHTML and fixing all problems that come with serialization to HTML (such as missing quotes in attributes, not closed tags etc.)
I will have to look into XMLSerializer tomorrow. Here is the code I ended up writing instead, in case anyone is interested (requires prototype and FireBug for unknown nodes):
function extractXML(node) {
switch (node.nodeType) {
case 1: return extractNodeXML(node);
case 2: return extractAttributeXML(node);
// 3 = Text node
case 3: return node.nodeValue;
// 8 = Comment node - ignore
case 8: return "";
case 9: return extractDocumentNodeXML(node);
case 10: return extractDocumentTypeXML(node);
default: console.log(node); return "Unkwon type: "+node.nodeType;
}
}
function extractNodeXML(node) {
var xml = "<"+node.nodeName;
$A(node.attributes).each(function (node) {xml += " "+extractXML(node)});
xml +=">"
$A(node.childNodes).each(function (node) {xml += extractXML(node)});
xml += "</"+node.nodeName+">"
return xml;
}
function extractAttributeXML(node) {
return node.nodeName+"=\""+node.nodeValue+"\""
}
function extractDocumentNodeXML(node) {
var xml = "<?xml version=\""+node.xmlVersion+"\" encoding=\""+node.xmlEncoding+"\"?>"
$A(node.childNodes).each(function (node) {xml += extractXML(node)});
return xml;
}
function extractDocumentTypeXML(node) {
return "<!DOCTYPE "+node.name+" PUBLIC \""+node.publicId+"\" \""+node.systemId+"\">"
}
Converting JSON to XML in JavaScript is blasphemy!
But if I had to do it I would use: http://code.google.com/p/x2js/
I haven't used this myself, but it seems like a good solution for anyone doing for a front-/back-end agnostic approach.
https://github.com/michaelkourlas/node-js2xmlparser