我有这个XML:
<dl>
<number>1</number>
<ref>r54</ref>
</dl>
<dl>
<number>2</number>
<ref>r67</ref>
</dl>
<dl>
<number>3</number>
<ref>r89</ref>
</dl>
我需要将Dl存储在包含dl的所有子值的数组中。 我的输出应该是:
dl: {
number: 1,
ref: r54
},
dl {
number: 1,
ref: r67
},
dl {
number: 1,
ref: r89
},
我正在尝试执行以下操作:
public getArrayDl(xml: Document, xpath: string) {
let array = [];
let i = 0;
let nodes = xml.evaluate(xpath, xml, null, XPathResult.ANY_TYPE, null);
let result = nodes.iterateNext();
while (result) {
array[i] = result.childNodes[0].nodeValue;
result = nodes.iterateNext();
i++;
}
return array;
}
但是它不起作用,有什么建议吗?
谢谢
答案 0 :(得分:0)
如果我正确理解这一点,则您正在尝试将XML段转换为JSON。
有许多可用的XML到JSON库。
充分利用它们,例如x2js
var xmlString = `<root><dl><number>1</number><ref>r54</ref></dl><dl><number>2</number><ref>r67</ref></dl><dl><number>3</number><ref>r89</ref></dl></root>`;
var x2js = new X2JS();
//console.log(x2js.xml_str2json(xmlString));
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlString, "text/xml");
var arr = [];
let nodes = xmlDoc.evaluate("//*[dl]", xmlDoc, null, XPathResult.ANY_TYPE, null);
let result = nodes.iterateNext();
while (result) {
arr.push(x2js.xml2json (result));
result = nodes.iterateNext();
}
console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/x2js/1.2.0/xml2json.js"></script>
PS:我用<root>
标记包裹了dl段,以使其成为有效的XML。要记住的事情,或在各个细分中进行迭代。