When operating XML files, we can use the Load method to directly Load the xml files, which is common in ie and ff. But it is an XML string, it will be different in the two browsers. in IE, you can directly use the LoadXML method to parse the XML string, and in FF, you need to use the parseFromString () of the DOMParser object () the method is
Var oParser = new DOMParser ();
XmlDoc = oParser. parseFromString (xmlStr, "text/xml ");
In order to be useful in both browsers, I think of the exception handling method of javascrui, that is, try... catch...
The Code is as follows:
Function toXML (strxml ){
Try {
XmlDoc = new ActiveXObject ("Microsoft. XMLDOM ");
XmlDoc. loadXML (strxml );
}
Catch (e ){
Var oParser = new DOMParser ();
XmlDoc = oParser. parseFromString (strxml, "text/xml ");
}
Return xmlDoc;
}
<Script type = "text/javascript"> function toXML (strxml) {try {var xmlDoc = new ActiveXObject ("Microsoft. XMLDOM "); // var xmlDoc = new ActiveXObject (" Msxml2.DOMDocument "); xmlDoc. loadXML (strxml);} catch (e) {var oParser = new DOMParser (); xmlDoc = oParser. parseFromString (strxml, "text/xml");} return xmlDoc ;} str = "<node1> <node1_1> 1400 </node1_1> <node1_2 id = 'n1 _ 2'> Default.htm </node1_2> </node1>" var xmlObj = toXML (str ); alert (xmlObj. childNodes [0]. firstChild. firstChild. nodeValue); script
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
Check that 1400 is displayed in both ie and ff !!
The Code is as follows:
Function FormatToXml (strXml ){
Var isIE = function (){
Var IE =/msie/I. test (navigator. userAgent );
Return IE;
}
Var Exc = function (){
Var XmlDoc = null;
If (isIE ())
{
XmlDoc = new ActiveXObject ("Microsoft. XMLDOM ");
XmlDoc. loadXML (strXml );
} Else {
// FireFox2.0 and Safari2.0
XmlDoc = (new DOMParser (). parseFromString (strXml, "text/xml ");
}
Return XmlDoc;
}
Return Exc ();
}
The functions are the same. They are used to parse xml strings in ie and ff. However, some people say that xml strings must be If xml version = "1.0" encoding = "gb2312"?>, The parsing results are inconsistent, so the above example does not contain these characters.