如何在 IE 和 Firefox 中解析 javascript 中的 XML? [英] How can I parse XML in javascript in both IE and firefox?

查看:20
本文介绍了如何在 IE 和 Firefox 中解析 javascript 中的 XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一段代码来解析 IE 和 firefox 中的 javascript.

I'm trying to write a single piece of code to parse javascript in both IE and firefox.

以下在 IE 中有效,在 Firefox 中正常运行

The following works in IE, and functions without complaining in firefox

function XmlDom(sXml){
    var oXml;
    if (window.ActiveXObject) {
        // ie
        oXml = new ActiveXObject("Microsoft.XMLDOM");
        oXml.resolveExternals = false;
        oXml.async = false;
        oXml.loadXML(sXml);
    }
    else if (window.DOMParser){

        var parser = new DOMParser(); 
        oXml = parser.parseFromString(sXml, "text/xml");

    }
return oXml
}

以下在 IE 中有效,但在 Firefox 下报错(因为 childNodes 不存在)

The following works in IE, but gives errors (because childNodes doesn't exist) under Firefox

var oXml = XmlDom(sourceXML);
var listHtml = "";
if (oXml.firstChild != null) {
    var childNodes = null;
    try {
        childNodes = oXml.lastChild.lastChild.firstChild.childNodes;
    }
    if (childNodes != null && childNodes.length > 0) {

        for (var i = 0; i < childNodes.length; i++) {

            var vehicleName = NodeText(SelectSingleNode(childNodes[i], 'VehicleName', 'VehicleName'));
            var vehicleId = NodeText(SelectSingleNode(childNodes[i], 'VehicleId', 'VehicleId'));

        }
    }
}

使用 jquery 在 firefox 下给了我正确的行为,但在 IE 中不太适用(它找到了正确的车辆数量,但每辆车都有一个空 ID 和名称)

Using jquery gives me correct behavior under firefox, but doesn't quite work in IE (it finds the correct number of vehicles, but each one has a null id and name)

 $(sourceXml).find("Table1").each(function() {
        var vehicleId = $(this).find("VehicleId").text();
        var vehicleName = $(this).find("VehicleName").text();
    });

我坚信这两种方法应该有效.但有些事情出错了.我想要一只手.

I firmly believe that both these approaches should work. But something is going wrong. I'd love a hand.

<?xml version="1.0" encoding="utf-16"?>
<DataSet>
  <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema"     xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:msprop="urn:schemas-microsoft-com:xml-msprop">
    <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
      <xs:complexType>
        <xs:choice minOccurs="0" maxOccurs="unbounded">
          <xs:element name="Table1">
            <xs:complexType>
              <xs:sequence>
                <xs:element name="VehicleId" msprop:metadatacolumnname="VehicleId" msprop:caption="VehicleId" type="xs:string" minOccurs="0" />
                <xs:element name="VehicleName" msprop:metadatacolumnname="VehicleName" msprop:caption="VehicleName" type="xs:string" minOccurs="0" />
            <xs:element name="SendAlarms" msprop:metadatacolumnname="SendAlarms" msprop:caption="SendAlarms" type="xs:string" minOccurs="0" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:choice>
  </xs:complexType>
  </xs:element>
  </xs:schema>
  <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"   xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
<NewDataSet>
  <Table1 diffgr:id="Table11" msdata:rowOrder="0" diffgr:hasChanges="inserted">
    <VehicleId>8</VehicleId>
    <VehicleName>AIS Gate</VehicleName>
    <SendAlarms>False</SendAlarms>
  </Table1>
  <Table1 diffgr:id="Table12" msdata:rowOrder="1" diffgr:hasChanges="inserted">
    <VehicleId>82</VehicleId>
    <VehicleName>Amigos</VehicleName>
    <SendAlarms>False</SendAlarms>
  </Table1> 
</NewDataSet>
</diffgr:diffgram>
</DataSet>

推荐答案

问题是 Firefox 的 XML 解析器没有忽略空白文本节点,而 IE 则是,这意味着 oXml.lastChild.lastChild 在事实上是一个文本节点并且没有子节点.我不知道如何指示在 Firefox(和其他浏览器)中找到的 DOMParser 忽略空格节点,因此您必须通过以下两种方式之一解决它:要么在传递之前删除空格将它传递给解析器的 parseFromString() 方法,或者您以过滤掉空白文本节点的方式遍历 XML DOM.

The problem is that Firefox's XML parser is not ignoring whitespace text nodes whereas IE's is, meaning that oXml.lastChild.lastChild is in fact a text node and has no children. There's no way I know of to instruct DOMParser found in Firefox (and other browsers) to ignore whitespace nodes, so you'll have to work round it in one of two ways: either you remove whitespace before passing it to the parser's parseFromString() method, or you traverse the XML DOM in such a way that you filter out whitespace text nodes.

Firefox 3.5 及更高版本支持 DOM 元素遍历 API,这意味着您可以使用诸如firstElementChildlastElementChildnextElementSiblingpreviousElementSibling.Firefox 3.5 还支持元素的 children 属性,它是作为元素的所有子节点的集合.Safari、Chrome 和 Opera 的最新版本(我不确定具体情况)也支持这些属性.

Firefox 3.5 and later supports the DOM Element Traversal API, meaning you can use properties like firstElementChild, lastElementChild, nextElementSibling and previousElementSibling. Firefox 3.5 also supports the children property of an element, which is the collection of all child nodes that are elements. Recent versions (I'm not sure of the specifics) of Safari, Chrome and Opera also support these properties.

使用标准 DOM 级别 1 方法并因此适用于所有浏览器的最后一个选项是在遍历 DOM 之前手动删除所有空白节点.以下函数将递归执行此操作:

One final option, which uses standard DOM Level 1 methods and will therefore work in all browsers, is to remove all whitespace nodes manually before traversing the DOM. The following function will do this recursively:

function removeWhiteSpaceNodes(node) {
    var child = node.firstChild, nextChild;
    while (child) {
        nextChild = child.nextSibling;
        if (child.nodeType == 3 && /^\s*$/.test(child.nodeValue)) {
            node.removeChild(child);
        } else if (child.hasChildNodes()) {
            removeWhiteSpaceNodes(child);
        }
        child = nextChild;
    }
}

这篇关于如何在 IE 和 Firefox 中解析 javascript 中的 XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆