XML 到 JavaScript 对象 [英] XML to JavaScript Object
问题描述
我正在寻找一个 JavaScript 库,可以解析 XML 字符串并将其转换为 JavaScript 对象.有什么好的?
I am looking for a JavaScript library that parses an XML string and converts it to a JavaScript object. What are some good ones?
推荐答案
以下函数解析 XML 并返回具有与 XML 对应的方案的 JavaScript 对象.具有相同名称的 XML 兄弟姐妹被折叠到数组中.具有可以在 arrayTags
参数(标签名称字符串数组)中找到的名称的节点总是生成数组,即使只有一个标签出现.arrayTags
可以省略.丢弃只有空格的文本节点.
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;
}
这篇关于XML 到 JavaScript 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!