Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
560 views
in Technique[技术] by (71.8m points)

javascript - 使用JavaScript对变量字符串进行XML解析(XML parsing of a variable string in JavaScript)

I have a variable string that contains well-formed and valid XML.

(我有一个包含格式正确且有效的XML的可变字符串 。)

I need to use JavaScript code to parse this feed.

(我需要使用JavaScript代码来解析此供稿。)

How can I accomplish this using (browser-compatible) JavaScript code?

(如何使用(浏览器兼容)JavaScript代码完成此操作?)

  ask by David Bonnici translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Updated answer for 2017

(更新了2017年的答案)

The following will parse an XML string into an XML document in all major browsers.

(下面将在所有主要浏览器中将XML字符串解析为XML文档。)

Unless you need support for IE <= 8 or some obscure browser, you could use the following function:

(除非需要支持IE <= 8或某些晦涩的浏览器,否则可以使用以下功能:)

function parseXml(xmlStr) {
   return new window.DOMParser().parseFromString(xmlStr, "text/xml");
}

If you need to support IE <= 8, the following will do the job:

(如果您需要支持IE <= 8,则可以执行以下操作:)

var parseXml;

if (typeof window.DOMParser != "undefined") {
    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 {
    throw new Error("No XML parser found");
}

Once you have a Document obtained via parseXml , you can use the usual DOM traversal methods/properties such as childNodes and getElementsByTagName() to get the nodes you want.

(通过parseXml获得Document parseXml ,就可以使用常规的DOM遍历方法/属性,例如childNodesgetElementsByTagName()来获取所需的节点。)

Example usage:

(用法示例:)

var xml = parseXml("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);

If you're using jQuery, from version 1.5 you can use its built-in parseXML() method, which is functionally identical to the function above.

(如果您使用的是jQuery,则从1.5版开始,您可以使用其内置的parseXML()方法,该方法在功能上与上述功能相同。)

var xml = $.parseXML("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...