所以我试图从xml文件中提取数据,如下所示:
<example>
<phrase>phrase1</phrase>
<word>
<definition>definition1</definition>
</word>
<word>
<definition>definition2</definition>
</word>
</example>
我希望能够将definition1和definition2作为数组的单独成员,现在我将它们合并为:definition1definition2
这是我的代码:
var $example = $xml.find("example");
$example.each(function(){
list.push($(this).children("word").children("definition").text());
});
有没有人有想法? 感谢
答案 0 :(得分:1)
如果要使用JQuery,则需要更改
$example.each(function(){
list.push($(this).children("word").children("definition").text());
});
到
$example.children("word").children("definition").each(
function() {
list.push($(this).text());
});
答案 1 :(得分:0)
查看此Fiddle.
$(document).ready(function() {
var xml =
'<example>' +
'<phrase>phrase1</phrase>' +
'<word>' +
'<definition>definition1</definition>' +
'</word>' +
'<word>' +
'<definition>definition2</definition>' +
'</word>' +
'</example>' +
'';
var xmlDoc = new DOMParser().parseFromString(xml, 'text/xml');
var x = xmlDoc.documentElement.childNodes;
var list = [];
for (i = 0; i < x.length; i++) {
if (x[i].nodeName == 'word') {
console.log(x[i].childNodes[0].innerHTML);
list.push(x[i].childNodes[0].innerHTML);
}
}
document.getElementById('demo').innerHTML = list;
console.log(list);
});
答案 2 :(得分:0)
jquery解决方案
$example.find("word > definition").map(function(){ return $(this).text()}).toArray()
var xml =
'<example>' +
'<phrase>phrase1</phrase>' +
'<word>' +
'<definition>definition1</definition>' +
'</word>' +
'<word>' +
'<definition>definition2</definition>' +
'</word>' +
'</example>' +
'';
var xmlDoc = new DOMParser().parseFromString(xml, 'text/xml');
var list = $("example > word > definition",xmlDoc).map(function(){ return $(this).text()}).toArray();
console.log(list);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
&#13;
vanila js解决方案
// Code goes here
var list = [];
var txt = `<example>
<phrase>phrase1</phrase>
<word>
<definition>definition1</definition>
</word>
<word>
<definition>definition2</definition>
</word>
</example>`;
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(txt, "text/xml");
} else // Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(txt);
}
var elements = xmlDoc.getElementsByTagName("definition");
[].forEach.call(elements, function(el) {
list.push(el.textContent)
});
console.log(list);
&#13;