从xml文件中获取子项的子项

时间:2016-07-20 08:40:58

标签: javascript arrays xml

所以我试图从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());
                });

有没有人有想法? 感谢

3 个答案:

答案 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()

&#13;
&#13;
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;
&#13;
&#13;

vanila js解决方案

&#13;
&#13;
// 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;
&#13;
&#13;