我試圖編寫一段代碼來在IE和Firefox中解析JavaScript。如何在IE和Firefox中解析JavaScript中的XML?
在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
}
在IE下工作,但給人的錯誤(因爲的childNodes不存在)的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和名稱)
$(sourceXml).find("Table1").each(function() {
var vehicleId = $(this).find("VehicleId").text();
var vehicleName = $(this).find("VehicleName").text();
});
我堅信這兩個辦法應該工作。但有些事情出錯了。我會愛一隻手。
<?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>
XML是什麼樣的? – 2010-11-24 23:42:32
添加了上面的XML。 – Erin 2010-11-24 23:51:24