如何使用jQuery解析XML集合

时间:2016-06-17 06:59:12

标签: javascript jquery xml

我有这个XML数组(或集合),它可以包含2个以上的项目:

<?xml version="1.0" encoding="utf-8"?>
<head>
  <word>
    <ID>1</ID>
    <answer>answer 1</answer>
    <question>Question 1</question>
  </word>
  <word>
    <ID>2</ID>
    <answer>answer 1</answer>
    <question>Question 2</question>
  </word>
</head>

我需要使用jQuery通过回答和集合在JavaScript集合中解析它。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

你的问题非常模糊,但也许这个例子可以帮助你:

(使用jquery解析并附加到表中的数据)

&#13;
&#13;
var datas = '<?xml version="1.0" encoding="utf-8"?>' + '<head>' + '<word>' + '<ID>1</ID>' + '<answer>answer 1</answer>' + '<question>Question 1</question>' + '</word>' + '<word>' + '<ID>2</ID>' + '<answer>answer 1</answer>' + '<question>Question 2</question>' + '</word>' + '</head>';

questions = $(datas).find('question');
answers = $(datas).find('answer');


for (var i = 0; i < questions.length; i++) {
  $('#table').append("<tr><td> " + questions[i].innerText + " </td> <td> " + answers[i].innerText + " </td></tr>")
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table">
  <tr>
    <th>Q</th>
    <th>A</th>
  </tr>
</table>
&#13;
&#13;
&#13;