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

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


当前回答

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

在您的示例中,情况有所不同,因为您希望从字符串变量而不是URL加载XML。然而,对于这个要求,Chrome应该像Mozilla一样工作(或者我听说过),并支持parseFromString()方法。

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

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

其他回答

更新:关于更正确的答案,请参阅Tim Down的答案。

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

一个非常基本的例子是:

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

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

注:如评论所指出;jQuery实际上不做任何XML解析,它依赖于DOM innerHTML方法,并将像解析任何HTML一样解析它,所以在XML中使用HTML元素名称时要小心。但我认为它对于简单的XML“解析”相当有效,但对于密集的或“动态的”XML解析可能不建议使用它,因为在这种情况下,您不知道将会出现哪些XML,并测试是否所有内容都按预期解析。

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

在您的示例中,情况有所不同,因为您希望从字符串变量而不是URL加载XML。然而,对于这个要求,Chrome应该像Mozilla一样工作(或者我听说过),并支持parseFromString()方法。

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

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

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

示例XML:

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

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

显然jQuery现在提供jQuery。parseXML http://api.jquery.com/jQuery.parseXML/ 从版本1.5开始

jQuery。parseXML(数据) 返回:XMLDocument

请看看XML DOM解析器(W3Schools)。这是一个关于XML DOM解析的教程。实际的DOM解析器因浏览器而异,但DOM API是标准化的,并保持相同(或多或少)。

如果可以限制自己使用Firefox,也可以使用E4X。它相对来说更容易使用,并且从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.