JavaScript中变量字符串的XML解析。

时间:2022-08-26 12:55:11

I have a variable string that contains well-formed and valid XML. I need to use JavaScript code to parse this feed.

我有一个包含格式良好且有效的XML的变量字符串。我需要使用JavaScript代码来解析这个提要。

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

如何使用(与浏览器兼容的)JavaScript代码实现这一点?

10 个解决方案

#1


87  

Update: For a more correct answer see Tim Down's answer.

更新:想要得到更正确的答案,请参阅Tim Down的答案。

Internet Explorer and, for example, Mozilla-based browsers expose different objects for XML parsing, so it's wise to use a JavaScript framework like jQuery to handle the cross-browsers differences.

Internet Explorer和基于mozilla的浏览器为XML解析公开了不同的对象,因此明智的做法是使用像jQuery这样的JavaScript框架来处理跨浏览器的差异。

A really basic example is:

一个非常基本的例子是:

var xml = "<music><album>Beethoven</album></music>";

var result = $(xml).find("album").text();

Note: As pointed out in comments; jQuery does not really do any XML parsing whatsoever, it relies on the DOM innerHTML method and will parse it like it would any HTML so be careful when using HTML element names in your XML. But I think it works fairly good for simple XML 'parsing', but it's probably not suggested for intensive or 'dynamic' XML parsing where you do not upfront what XML will come down and this tests if everything parses as expected.

注:如评论所指出;jQuery实际上不做任何XML解析,它依赖于DOM innerHTML方法,它将像任何HTML一样解析它,所以在XML中使用HTML元素名称时要小心。但我认为它对于简单的XML“解析”非常有效,但对于密集的或“动态的”XML解析,可能不建议使用它。在这种情况下,如果一切都按照预期进行解析,就不需要预先考虑XML会下降到什么程度,然后进行测试。

#2


304  

Updated answer for 2017

2017年负责更新

The following will parse an XML string into an XML document in all major browsers. Unless you need support for IE <= 8 or some obscure browser, you could use the following function:

下面将在所有主要浏览器中将XML字符串解析为XML文档。除非你需要支持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获得了一个文档,就可以使用通常的DOM遍历方法/属性(如子节点和getElementsByTagName())来获取所需的节点。

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);

#3


19  

Most examples on the web (and some presented above) show how to load an XML from a file in a browser compatible manner. This proves easy, except in the case of Google Chrome which does not support the document.implementation.createDocument() method. When using Chrome, in order to load an XML file into a XmlDocument object, you need to use the inbuilt XmlHttp object and then load the file by passing it's URI.

web上的大多数示例(以及上面介绍的一些示例)展示了如何以浏览器兼容的方式从文件中加载XML。这证明很容易,但谷歌Chrome不支持document.implementation.createDocument()方法。使用Chrome时,为了将XML文件加载到XmlDocument对象中,需要使用内置的XmlHttp对象,然后通过传递该文件的URI来加载该文件。

In your case, the scenario is different, because you want to load the XML from a string variable, not a URL. For this requirement however, Chrome supposedly works just like Mozilla (or so I've heard) and supports the parseFromString() method.

在您的示例中,场景是不同的,因为您希望从字符串变量而不是URL加载XML。但是,对于这个需求,Chrome的工作原理就像Mozilla(或者我听说过的),并且支持parseFromString()方法。

Here is a function I use (it's part of the Browser compatibility library I'm currently building):

下面是我使用的一个函数(它是我目前正在构建的浏览器兼容性库的一部分):

function LoadXMLString(xmlString)
{
  // ObjectExists checks if the passed parameter is not null.
  // isString (as the name suggests) checks if the type is a valid string.
  if (ObjectExists(xmlString) && isString(xmlString))
  {
    var xDoc;
    // The GetBrowserType function returns a 2-letter code representing
    // ...the type of browser.
    var bType = GetBrowserType();

    switch(bType)
    {
      case "ie":
        // This actually calls into a function that returns a DOMDocument 
        // on the basis of the MSXML version installed.
        // Simplified here for illustration.
        xDoc = new ActiveXObject("MSXML2.DOMDocument")
        xDoc.async = false;
        xDoc.loadXML(xmlString);
        break;
      default:
        var dp = new DOMParser();
        xDoc = dp.parseFromString(xmlString, "text/xml");
        break;
    }
    return xDoc;
  }
  else
    return null;
}

#4


13  

Marknote is a nice lightweight cross-browser JavaScript XML parser. It's object-oriented and it's got plenty of examples, plus the API is documented. It's fairly new, but it has worked nicely in one of my projects so far. One thing I like about it is that it will read XML directly from strings or URLs and you can also use it to convert the XML into JSON.

Marknote是一个很好的轻量级跨浏览器JavaScript XML解析器。它是面向对象的,并且有很多例子,而且API是有文档记录的。它是相当新的,但是到目前为止它在我的一个项目中运行得很好。我喜欢的一点是,它可以直接从字符串或url读取XML,还可以使用它将XML转换成JSON。

Here's an example of what you can do with Marknote:

这里有一个使用Marknote的例子:

var str = '<books>' +
          '  <book title="A Tale of Two Cities"/>' +
          '  <book title="1984"/>' +
          '</books>';

var parser = new marknote.Parser();
var doc = parser.parse(str);

var bookEls = doc.getRootElement().getChildElements();

for (var i=0; i<bookEls.length; i++) {
    var bookEl = bookEls[i];
    // alerts "Element name is 'book' and book title is '...'"
    alert("Element name is '" + bookEl.getName() + 
        "' and book title is '" + 
        bookEl.getAttributeValue("title") + "'"
    );
}

#5


8  

I've always used the approach below which works in IE and Firefox.

我一直在IE和Firefox中使用下面的方法。

Example XML:

示例XML:

<fruits>
  <fruit name="Apple" colour="Green" />
  <fruit name="Banana" colour="Yellow" />
</fruits>

JavaScript:

JavaScript:

function getFruits(xml) {
  var fruits = xml.getElementsByTagName("fruits")[0];
  if (fruits) {
    var fruitsNodes = fruits.childNodes;
    if (fruitsNodes) {
      for (var i = 0; i < fruitsNodes.length; i++) {
        var name = fruitsNodes[i].getAttribute("name");
        var colour = fruitsNodes[i].getAttribute("colour");
        alert("Fruit " + name + " is coloured " + colour);
      }
    }
  }
}

#6


8  

Apparently jQuery now provides jQuery.parseXML http://api.jquery.com/jQuery.parseXML/ as of version 1.5

显然,jQuery现在提供了jQuery。第1.5版的parseXML http://api.jquery.com/jQuery.parseXML/

jQuery.parseXML( data ) Returns: XMLDocument

jQuery。parseXML(数据)返回:XMLDocument。

#7


2  

Please take a look at XML DOM Parser (W3Schools). It's a tutorial on XML DOM parsing. The actual DOM parser differs from browser to browser but the DOM API is standardised and remains the same (more or less).

请查看XML DOM解析器(W3Schools)。这是关于XML DOM解析的教程。实际的DOM解析器不同于浏览器,但是DOM API是标准化的,并且保持不变(或多或少)。

Alternatively use E4X if you can restrict yourself to Firefox. It's relatively easier to use and it's part of JavaScript since version 1.6. Here is a small sample usage...

或者使用E4X,如果您可以将自己限制在Firefox中。它使用起来相对比较容易,并且是自1.6版本以来JavaScript的一部分。这里有一个小的示例用法……

//Using E4X
var xmlDoc=new XML();
xmlDoc.load("note.xml");
document.write(xmlDoc.body); //Note: 'body' is actually a tag in note.xml,
//but it can be accessed as if it were a regular property of xmlDoc.

#8


0  

<script language="JavaScript">
function importXML()
{
    if (document.implementation && document.implementation.createDocument)
    {
            xmlDoc = document.implementation.createDocument("", "", null);
            xmlDoc.onload = createTable;
    }
    else if (window.ActiveXObject)
    {
            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.onreadystatechange = function () {
                    if (xmlDoc.readyState == 4) createTable()
            };
    }
    else
    {
            alert('Your browser can\'t handle this script');
            return;
    }
    xmlDoc.load("emperors.xml");
}

function createTable()
{
    var theData="";
    var x = xmlDoc.getElementsByTagName('emperor');
    var newEl = document.createElement('TABLE');
    newEl.setAttribute('cellPadding',3);
    newEl.setAttribute('cellSpacing',0);
    newEl.setAttribute('border',1);
    var tmp = document.createElement('TBODY');
    newEl.appendChild(tmp);
    var row = document.createElement('TR');
    for (j=0;j<x[0].childNodes.length;j++)
    {
            if (x[0].childNodes[j].nodeType != 1) continue;
            var container = document.createElement('TH');
            theData = document.createTextNode(x[0].childNodes[j].nodeName);
            container.appendChild(theData);
            row.appendChild(container);
    }
    tmp.appendChild(row);
    for (i=0;i<x.length;i++)
    {
            var row = document.createElement('TR');
            for (j=0;j<x[i].childNodes.length;j++)
            {
                    if (x[i].childNodes[j].nodeType != 1) continue;
                    var container = document.createElement('TD');
                    var theData = document.createTextNode(x[i].childNodes[j].firstChild.nodeValue);
                    container.appendChild(theData);
                    row.appendChild(container);
            }
            tmp.appendChild(row);
    }
    document.getElementById('writeroot').appendChild(newEl);
}
</script>
</HEAD>

<BODY onLoad="javascript:importXML();">
<p id=writeroot> </p>
</BODY>

For more info refer this http://www.easycodingclub.com/xml-parser-in-javascript/javascript-tutorials/

要了解更多信息,请参考这个http://www.easycodingclub.com/xml- parserin - javascript/javascript/javascript -tutorials/。

#9


0  

Disclaimer : I've created fast-xml-parser

声明:我创建了快速xml解析器

I have created fast-xml-parser to parse a XML string into JS/JSON object or intermediate traversal object. It is expected to be compatible in all the browsers (however tested on Chrome, Firefox, and IE only).

我创建了快速XML解析器,将XML字符串解析为JS/JSON对象或中间遍历对象。它有望在所有浏览器中兼容(不过只在Chrome、Firefox和IE上测试)。

Usage

使用

var options = { //default
    attrPrefix : "@_",
    attrNodeName: false,
    textNodeName : "#text",
    ignoreNonTextNodeAttr : true,
    ignoreTextNodeAttr : true,
    ignoreNameSpace : true,
    ignoreRootElement : false,
    textNodeConversion : true,
    textAttrConversion : false,
    arrayMode : false
};

if(parser.validate(xmlData)){//optional
    var jsonObj = parser.parse(xmlData, options);
}

//Intermediate obj
var tObj = parser.getTraversalObj(xmlData,options);
:
var jsonObj = parser.convertToJson(tObj);

Note: It doesn't use DOM parser but parse the string using RE and convert it into JS/JSON object.

注意:它不使用DOM解析器,而是使用RE解析字符串并将其转换为JS/JSON对象。

Try it online, CDN

试一试在线,CDN

#10


-1  

You can also through the jquery function($.parseXML) to manipulate xml string

您还可以通过jquery函数($.parseXML)来操作xml字符串

example javascript:

示例javascript:

var xmlString = '<languages><language name="c"></language><language name="php"></language></languages>';
var xmlDoc = $.parseXML(xmlString);
$(xmlDoc).find('name').each(function(){
    console.log('name:'+$(this).attr('name'))
})

#1


87  

Update: For a more correct answer see Tim Down's answer.

更新:想要得到更正确的答案,请参阅Tim Down的答案。

Internet Explorer and, for example, Mozilla-based browsers expose different objects for XML parsing, so it's wise to use a JavaScript framework like jQuery to handle the cross-browsers differences.

Internet Explorer和基于mozilla的浏览器为XML解析公开了不同的对象,因此明智的做法是使用像jQuery这样的JavaScript框架来处理跨浏览器的差异。

A really basic example is:

一个非常基本的例子是:

var xml = "<music><album>Beethoven</album></music>";

var result = $(xml).find("album").text();

Note: As pointed out in comments; jQuery does not really do any XML parsing whatsoever, it relies on the DOM innerHTML method and will parse it like it would any HTML so be careful when using HTML element names in your XML. But I think it works fairly good for simple XML 'parsing', but it's probably not suggested for intensive or 'dynamic' XML parsing where you do not upfront what XML will come down and this tests if everything parses as expected.

注:如评论所指出;jQuery实际上不做任何XML解析,它依赖于DOM innerHTML方法,它将像任何HTML一样解析它,所以在XML中使用HTML元素名称时要小心。但我认为它对于简单的XML“解析”非常有效,但对于密集的或“动态的”XML解析,可能不建议使用它。在这种情况下,如果一切都按照预期进行解析,就不需要预先考虑XML会下降到什么程度,然后进行测试。

#2


304  

Updated answer for 2017

2017年负责更新

The following will parse an XML string into an XML document in all major browsers. Unless you need support for IE <= 8 or some obscure browser, you could use the following function:

下面将在所有主要浏览器中将XML字符串解析为XML文档。除非你需要支持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获得了一个文档,就可以使用通常的DOM遍历方法/属性(如子节点和getElementsByTagName())来获取所需的节点。

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);

#3


19  

Most examples on the web (and some presented above) show how to load an XML from a file in a browser compatible manner. This proves easy, except in the case of Google Chrome which does not support the document.implementation.createDocument() method. When using Chrome, in order to load an XML file into a XmlDocument object, you need to use the inbuilt XmlHttp object and then load the file by passing it's URI.

web上的大多数示例(以及上面介绍的一些示例)展示了如何以浏览器兼容的方式从文件中加载XML。这证明很容易,但谷歌Chrome不支持document.implementation.createDocument()方法。使用Chrome时,为了将XML文件加载到XmlDocument对象中,需要使用内置的XmlHttp对象,然后通过传递该文件的URI来加载该文件。

In your case, the scenario is different, because you want to load the XML from a string variable, not a URL. For this requirement however, Chrome supposedly works just like Mozilla (or so I've heard) and supports the parseFromString() method.

在您的示例中,场景是不同的,因为您希望从字符串变量而不是URL加载XML。但是,对于这个需求,Chrome的工作原理就像Mozilla(或者我听说过的),并且支持parseFromString()方法。

Here is a function I use (it's part of the Browser compatibility library I'm currently building):

下面是我使用的一个函数(它是我目前正在构建的浏览器兼容性库的一部分):

function LoadXMLString(xmlString)
{
  // ObjectExists checks if the passed parameter is not null.
  // isString (as the name suggests) checks if the type is a valid string.
  if (ObjectExists(xmlString) && isString(xmlString))
  {
    var xDoc;
    // The GetBrowserType function returns a 2-letter code representing
    // ...the type of browser.
    var bType = GetBrowserType();

    switch(bType)
    {
      case "ie":
        // This actually calls into a function that returns a DOMDocument 
        // on the basis of the MSXML version installed.
        // Simplified here for illustration.
        xDoc = new ActiveXObject("MSXML2.DOMDocument")
        xDoc.async = false;
        xDoc.loadXML(xmlString);
        break;
      default:
        var dp = new DOMParser();
        xDoc = dp.parseFromString(xmlString, "text/xml");
        break;
    }
    return xDoc;
  }
  else
    return null;
}

#4


13  

Marknote is a nice lightweight cross-browser JavaScript XML parser. It's object-oriented and it's got plenty of examples, plus the API is documented. It's fairly new, but it has worked nicely in one of my projects so far. One thing I like about it is that it will read XML directly from strings or URLs and you can also use it to convert the XML into JSON.

Marknote是一个很好的轻量级跨浏览器JavaScript XML解析器。它是面向对象的,并且有很多例子,而且API是有文档记录的。它是相当新的,但是到目前为止它在我的一个项目中运行得很好。我喜欢的一点是,它可以直接从字符串或url读取XML,还可以使用它将XML转换成JSON。

Here's an example of what you can do with Marknote:

这里有一个使用Marknote的例子:

var str = '<books>' +
          '  <book title="A Tale of Two Cities"/>' +
          '  <book title="1984"/>' +
          '</books>';

var parser = new marknote.Parser();
var doc = parser.parse(str);

var bookEls = doc.getRootElement().getChildElements();

for (var i=0; i<bookEls.length; i++) {
    var bookEl = bookEls[i];
    // alerts "Element name is 'book' and book title is '...'"
    alert("Element name is '" + bookEl.getName() + 
        "' and book title is '" + 
        bookEl.getAttributeValue("title") + "'"
    );
}

#5


8  

I've always used the approach below which works in IE and Firefox.

我一直在IE和Firefox中使用下面的方法。

Example XML:

示例XML:

<fruits>
  <fruit name="Apple" colour="Green" />
  <fruit name="Banana" colour="Yellow" />
</fruits>

JavaScript:

JavaScript:

function getFruits(xml) {
  var fruits = xml.getElementsByTagName("fruits")[0];
  if (fruits) {
    var fruitsNodes = fruits.childNodes;
    if (fruitsNodes) {
      for (var i = 0; i < fruitsNodes.length; i++) {
        var name = fruitsNodes[i].getAttribute("name");
        var colour = fruitsNodes[i].getAttribute("colour");
        alert("Fruit " + name + " is coloured " + colour);
      }
    }
  }
}

#6


8  

Apparently jQuery now provides jQuery.parseXML http://api.jquery.com/jQuery.parseXML/ as of version 1.5

显然,jQuery现在提供了jQuery。第1.5版的parseXML http://api.jquery.com/jQuery.parseXML/

jQuery.parseXML( data ) Returns: XMLDocument

jQuery。parseXML(数据)返回:XMLDocument。

#7


2  

Please take a look at XML DOM Parser (W3Schools). It's a tutorial on XML DOM parsing. The actual DOM parser differs from browser to browser but the DOM API is standardised and remains the same (more or less).

请查看XML DOM解析器(W3Schools)。这是关于XML DOM解析的教程。实际的DOM解析器不同于浏览器,但是DOM API是标准化的,并且保持不变(或多或少)。

Alternatively use E4X if you can restrict yourself to Firefox. It's relatively easier to use and it's part of JavaScript since version 1.6. Here is a small sample usage...

或者使用E4X,如果您可以将自己限制在Firefox中。它使用起来相对比较容易,并且是自1.6版本以来JavaScript的一部分。这里有一个小的示例用法……

//Using E4X
var xmlDoc=new XML();
xmlDoc.load("note.xml");
document.write(xmlDoc.body); //Note: 'body' is actually a tag in note.xml,
//but it can be accessed as if it were a regular property of xmlDoc.

#8


0  

<script language="JavaScript">
function importXML()
{
    if (document.implementation && document.implementation.createDocument)
    {
            xmlDoc = document.implementation.createDocument("", "", null);
            xmlDoc.onload = createTable;
    }
    else if (window.ActiveXObject)
    {
            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.onreadystatechange = function () {
                    if (xmlDoc.readyState == 4) createTable()
            };
    }
    else
    {
            alert('Your browser can\'t handle this script');
            return;
    }
    xmlDoc.load("emperors.xml");
}

function createTable()
{
    var theData="";
    var x = xmlDoc.getElementsByTagName('emperor');
    var newEl = document.createElement('TABLE');
    newEl.setAttribute('cellPadding',3);
    newEl.setAttribute('cellSpacing',0);
    newEl.setAttribute('border',1);
    var tmp = document.createElement('TBODY');
    newEl.appendChild(tmp);
    var row = document.createElement('TR');
    for (j=0;j<x[0].childNodes.length;j++)
    {
            if (x[0].childNodes[j].nodeType != 1) continue;
            var container = document.createElement('TH');
            theData = document.createTextNode(x[0].childNodes[j].nodeName);
            container.appendChild(theData);
            row.appendChild(container);
    }
    tmp.appendChild(row);
    for (i=0;i<x.length;i++)
    {
            var row = document.createElement('TR');
            for (j=0;j<x[i].childNodes.length;j++)
            {
                    if (x[i].childNodes[j].nodeType != 1) continue;
                    var container = document.createElement('TD');
                    var theData = document.createTextNode(x[i].childNodes[j].firstChild.nodeValue);
                    container.appendChild(theData);
                    row.appendChild(container);
            }
            tmp.appendChild(row);
    }
    document.getElementById('writeroot').appendChild(newEl);
}
</script>
</HEAD>

<BODY onLoad="javascript:importXML();">
<p id=writeroot> </p>
</BODY>

For more info refer this http://www.easycodingclub.com/xml-parser-in-javascript/javascript-tutorials/

要了解更多信息,请参考这个http://www.easycodingclub.com/xml- parserin - javascript/javascript/javascript -tutorials/。

#9


0  

Disclaimer : I've created fast-xml-parser

声明:我创建了快速xml解析器

I have created fast-xml-parser to parse a XML string into JS/JSON object or intermediate traversal object. It is expected to be compatible in all the browsers (however tested on Chrome, Firefox, and IE only).

我创建了快速XML解析器,将XML字符串解析为JS/JSON对象或中间遍历对象。它有望在所有浏览器中兼容(不过只在Chrome、Firefox和IE上测试)。

Usage

使用

var options = { //default
    attrPrefix : "@_",
    attrNodeName: false,
    textNodeName : "#text",
    ignoreNonTextNodeAttr : true,
    ignoreTextNodeAttr : true,
    ignoreNameSpace : true,
    ignoreRootElement : false,
    textNodeConversion : true,
    textAttrConversion : false,
    arrayMode : false
};

if(parser.validate(xmlData)){//optional
    var jsonObj = parser.parse(xmlData, options);
}

//Intermediate obj
var tObj = parser.getTraversalObj(xmlData,options);
:
var jsonObj = parser.convertToJson(tObj);

Note: It doesn't use DOM parser but parse the string using RE and convert it into JS/JSON object.

注意:它不使用DOM解析器,而是使用RE解析字符串并将其转换为JS/JSON对象。

Try it online, CDN

试一试在线,CDN

#10


-1  

You can also through the jquery function($.parseXML) to manipulate xml string

您还可以通过jquery函数($.parseXML)来操作xml字符串

example javascript:

示例javascript:

var xmlString = '<languages><language name="c"></language><language name="php"></language></languages>';
var xmlDoc = $.parseXML(xmlString);
$(xmlDoc).find('name').each(function(){
    console.log('name:'+$(this).attr('name'))
})