该函数直接读取XMLDocument
(或文档节点/元素)的DOM属性,以完全准确地构建JSON,而不是尝试猜测或匹配。请传递XMLHttpRequest
中的responseXML
,而不是responseText
。
xml2json(xmlDoc)
如果你只有一串XML字符串,而不是一个XMLDocument
,jQuery会将你的文本转换为一个。
xml2json($(xmlString)[0])
attributes
对象中作为属性。children
数组中。attributes
或children
,但文本将在text
属性中。{
// Always present
"name": "FancyElement",
"type": "Element",
// If present
"attributes: {
"attr1": "val1",
"attr2": "val2"
},
"children": [...],
"text": "buncha fancy words"
}
function xml2json(xml) {
try {
const types = [null,
"Element",
"Attribute",
"Text",
"CDATA",
"EntityReference", // Deprecated
"Entity", // Deprecated
"ProcessingInstruction",
"Comment",
"Document",
"DocumentType",
"DocumentFragment",
"Notation" // Deprecated
];
var o = {};
o.name = xml.nodeName;
o.type = types[xml.nodeType];
if (xml.nodeType == 3 ||
xml.nodeType == 4 ||
xml.nodeType == 8 ) {
o.text = xml.textContent;
} else {
if (xml.attributes) {
o.attributes = {};
for (const a of xml.attributes) {
o.attributes[a.name] = a.value;
}
}
if (xml.childNodes.length) {
o.children = [];
for (const x of xml.childNodes) {
o.children.push(xml2json(x))
}
}
}
return (o);
} catch (e) {
alert('Error in xml2json. See console for details.');
console.log('Error in xml2json processing node:');
console.log(o);
console.log('Error:');
console.log(e);
}
}
var doc = document.getElementById("doc");
var out = document.getElementById("out");
out.innerText = JSON.stringify(xml2json(doc), null, 2);
/* Let's process the whole Code Snippet #document, why not?
* Yes, the JSON we just put in the document body and all
* this code is encoded in the JSON in the console.
* In that copy you can see why the XML DOM will all be one line.
* The JSON in the console has "\n" nodes all throughout.
*/
console.log(xml2json(document));
#doc,
#out {
border: 1px solid black;
}
<div id="doc"><!-- The XML DOM will all be on one line --><div personality="bubbly" relevance=42>This text is valid for HTML.<span>But it probably shouldn't be siblings to an element in XML.</span></div></div>
<pre id="out"></pre>
最好的方法是使用服务器端,因为客户端不适用于所有场景。我试图使用 JavaScript 构建在线 json 到 xml 和 xml 到 json 转换器,但几乎无法在所有情况下正常工作。最终我使用 ASP.MVC 中的 Newtonsoft 在服务器端进行了转换。这是在线转换器 http://techfunda.com/Tools/XmlToJson。