[英]Get children of children from xml file
so im trying to extract data from a xml file which looks like this: 所以我试图从看起来像这样的xml文件中提取数据:
<example>
<phrase>phrase1</phrase>
<word>
<definition>definition1</definition>
</word>
<word>
<definition>definition2</definition>
</word>
</example>
I want to be able to put definition1 and definition2 as seperate members of an array, for now i get them merged like this: definition1definition2 我希望能够将definition1和definition2放置为数组的单独成员,现在我将它们像这样合并:definition1definition2
this is my code: 这是我的代码:
var $example = $xml.find("example");
$example.each(function(){
list.push($(this).children("word").children("definition").text());
});
Does anyone have an idea? 有人有主意吗? thanks
谢谢
If you want to use JQuery, you need to change the 如果要使用JQuery,则需要更改
$example.each(function(){
list.push($(this).children("word").children("definition").text());
});
to 至
$example.children("word").children("definition").each(
function() {
list.push($(this).text());
});
Check out this 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);
});
jquery solution 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);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
vanila js solution 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.