简体   繁体   English

如何在IE和Firefox中解析javascript中的XML?

[英]How can I parse XML in javascript in both IE and firefox?

I'm trying to write a single piece of code to parse javascript in both IE and firefox. 我正在尝试编写一段代码来解析IE和Firefox中的javascript。

The following works in IE, and functions without complaining in firefox 以下适用于IE,并且功能无需在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
}

The following works in IE, but gives errors (because childNodes doesn't exist) under Firefox 以下适用于IE,但在Firefox下会出现错误(因为childNodes不存在)

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

        }
    }
}

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) 使用jquery给我在firefox下的正确行为,但在IE中不能正常工作(它找到正确数量的车辆,但每个都有一个空id和名称)

 $(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>

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. 问题是Firefox的XML解析器没有忽略空白文本节点,而IE是,这意味着oXml.lastChild.lastChild实际上是一个文本节点而且没有子节点。 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(和其他浏览器)中找到的DOMParser忽略空白节点,因此您必须以两种方式之一解决它:在将空格传递给解析器的parseFromString()之前删除空格方法,或者以过滤空白文本节点的方式遍历XML DOM。

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及更高版本支持DOM Element Traversal API ,这意味着您可以使用firstElementChildlastElementChildnextElementSiblingpreviousElementSibling等属性。 Firefox 3.5 also supports the children property of an element, which is the collection of all child nodes that are elements. Firefox 3.5还支持元素的children属性,该元素是作为元素的所有子节点的集合。 Recent versions (I'm not sure of the specifics) of Safari, Chrome and Opera also support these properties. Safari,Chrome和Opera的最新版本(我不确定具体细节)也支持这些属性。

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. 最后一个选项使用标准DOM Level 1方法,因此可以在所有浏览器中使用,它是在遍历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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM