如何在 JavaScript 中将字符串转换为 XML 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3054108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert string to XML object in JavaScript?
提问by Hyman Roscoe
I am aware of thisquestion already existing, but it has given me no luck.
我知道这个问题已经存在,但它没有给我带来任何运气。
I have an application which loads a physicial XML document via the following method:
我有一个通过以下方法加载物理 XML 文档的应用程序:
jQuery.ajax({
type: "GET",
url: fileName,
dataType: "xml",
success: function (data) {
// etc...
}
});
I parse the XML and convert it into a string which is saved into a variable so that it can easily be stored in a database. How can I now convert the data in this variable back into an XML object so that it can be parsed as such?
我解析 XML 并将其转换为字符串,然后将其保存到变量中,以便可以轻松地将其存储在数据库中。我现在如何将这个变量中的数据转换回 XML 对象,以便可以这样解析?
回答by Tim Down
Non-jQuery version:
非 jQuery 版本:
var parseXml;
if (window.DOMParser) {
parseXml = function(xmlStr) {
return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
};
} else if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) {
parseXml = function(xmlStr) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
};
} else {
parseXml = function() { return null; }
}
var xmlDoc = parseXml("<foo>Stuff</foo>");
if (xmlDoc) {
window.alert(xmlDoc.documentElement.nodeName);
}
Since jQuery 1.5, you can use jQuery.parseXML(), which works in exactly the same way as the above code:
从 jQuery 1.5 开始,您可以使用jQuery.parseXML(),其工作方式与上述代码完全相同:
var xmlDoc = jQuery.parseXML("<foo>Stuff</foo>");
if (xmlDoc) {
window.alert(xmlDoc.documentElement.nodeName);
}
回答by artrol
With jquery, you can use $.parseXML(str), https://api.jquery.com/jQuery.parseXML/
使用jQuery,您可以使用$.parseXML(str),https://api.jquery.com/jQuery.parseXML/
回答by patrickmcgraw
If it's still in XML format you should be able to just wrap it in the jQuery function and start using jQuery to parse through it. For example:
如果它仍然是 XML 格式,您应该能够将它包装在 jQuery 函数中并开始使用 jQuery 来解析它。例如:
$(xmlStringFromDB).find('foo');

