我正在尝试将xml文件的一部分放入javascript数组中。我已经尝试了很多教程,但我无法让它工作。 这是我想要使用的xml文件的一部分:
<answers>
<answer id="0">hello</answer>
<answer id="1">goodbye</answer>
</answers>
我想在javascript数组中使用答案,如:
var FAnswers = new Array("hello","goodbye");
有没有人知道一个简单的小javascript来完成这项工作?
答案 0 :(得分:3)
以下功能应该可以解决问题:
function get_answers_from_xml_string(xml_string) {
// Parse the XML string into a XMLDocument
var doc = window.DOMParser
? new DOMParser().parseFromString(xml_string, 'text/xml') // Standard
: new ActiveXObject('Microsoft.XMLDOM').loadXML(xml_string); // IE
// Find the answer nodes
var answers_nodes = doc.getElementsByTagName('answer');
var answers = [];
// Loop through them and save their text content into an array
for (var i = 0; i < answers_nodes.length; i++) {
answers.push(answers_nodes[i].firstChild.data)
}
return answers;
}
只需将包含带答案的XML的字符串传递给它,它将返回一个数组:
var xml_string = '<answers><answer id="0">hello</answer><answer id="1">goodbye</answer></answers>';
var answers = get_answers_from_xml_string(xml_string);
// answers == ["hello", "goodbye"]
答案 1 :(得分:1)
所以你需要在javascript中解析XML。看看我刚才做的这个例子:
// Some XML, say loaded with AJAX, etc.
var str = '<response><answers><answer id="0">hello</answer><answer id="1">goodbye</answer></answers><data id="2341-63">Test data</data></response>';
var parser, xml;
if (window.DOMParser) {
parser = new DOMParser();
xml = parser.parseFromString(str, 'text/xml');
}
else { // IE
xml = new ActiveXObject('Microsoft.XMLDOM');
xml.async = false;
xml.loadXML(str);
}
var nodes = xml.getElementsByTagName('answer');
var i, l = nodes.length, answers = [];
for (i = 0; i < l; i++) {
answers.push(nodes[i].childNodes[0].nodeValue);
}
console.log(answers) // ["hello", "goodbye"]
答案 2 :(得分:0)
根据the answer to this question,您需要做类似的事情(假设您通过XHR加载XML):
// get XML
var xml = xhr.responseXML;
var target = new Array();
// get answers
var answers= xml.getElementsByTagName("answer");
for (var i = 0; i < answers.length; i++) {
target.push(answers[i].nodeValue);
}
答案 3 :(得分:0)
How about this way: The simplest -
var xml = "<answers><answer id='0'>hello</answer><answer id='1'>goodbye</answer></answers>";
document.write (xml);
var doc = document.getElementsByTagName('answer');
var arrayAnswers = [];
for(var i=0, len = doc.length; i < len; i++)
{
arrayAnswers.push(doc[i]);
}
alert(arrayAnswers[0].innerHTML);
alert(arrayAnswers[1].innerHTML);