jQuery不会使用名为option的节点解析xml [英] jQuery won't parse xml with nodes called option
问题描述
我正在使用jQuery解析一些XML,如下所示:
I'm using jQuery to parse some XML, like so:
function enumOptions(xml) {
$(xml).find("animal").each(function(){
alert($(this).text());
});
}
enumOptions("<root><animal>cow</animal><animal>squirrel</animal></root>");
这很有用。但是,如果我尝试查找名为option的节点,则它不起作用:
This works great. However if I try and look for nodes called "option" then it doesn't work:
function enumOptions(xml) {
$(xml).find("option").each(function(){
alert($(this).text());
});
}
enumOptions("<root><option>cow</option><option>squirrel</option></root>");
没有错误,只是没有得到任何警报,好像找不到任何东西。它只适用于名为选项的节点,我测试的其他所有工作都正常!
There's no error, just nothing gets alerted, as if the find isn't finding anything. It only does it for nodes called option everything else I tested works ok!
我正在使用当前版本的jQuery - 1.4.2。
I'm using the current version of jQuery - 1.4.2.
任何人有任何想法吗?
TIA。
bg
推荐答案
更新
jQuery已建立此方法在现在。您可以使用
jQuery has this method built-in now. You can use
$.parseXML("..")
从字符串构造XML DOM。
to construct the XML DOM from a string.
jQuery依赖于使用 innerHTML
的HTML DOM来解析当标记名与HTML中的标记名冲突时可能具有不可靠结果的文档。
jQuery relies on the HTML DOM using innerHTML
to parse the document which can have unreliable results when tag names collide with those in HTML.
相反,您可以使用正确的XML解析器来首先解析文档,然后使用jQuery进行查询。下面的方法将以跨浏览器的方式解析有效的XML文档:
Instead, you can use a proper XML parser to first parse the document, and then use jQuery for querying. The method below will parse a valid XML document in a cross-browser fashion:
// http://www.w3schools.com/dom/dom_parser.asp
function parseXML(text) {
var doc;
if(window.DOMParser) {
var parser = new DOMParser();
doc = parser.parseFromString(text, "text/xml");
}
else if(window.ActiveXObject) {
doc = new ActiveXObject("Microsoft.XMLDOM");
doc.async = "false";
doc.loadXML(text);
}
else {
throw new Error("Cannot parse XML");
}
return doc;
}
构建XML DOM后,jQuery可以正常使用 - http://jsfiddle.net/Rz7Uv/
Once the XML DOM is constructed, jQuery can be used as normal - http://jsfiddle.net/Rz7Uv/
var text = "<root><option>cow</option><option>squirrel</option></root>";
var xml = parseXML(text);
$(xml).find("option"); // selects <option>cow</option>, <option>squirrel</option>
这篇关于jQuery不会使用名为option的节点解析xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!