Home > Web Front-end > JS Tutorial > body text

JavaScript function to parse xml string_javascript skills

WBOY
Release: 2016-05-16 19:04:19
Original
1089 people have browsed it

But it is an XML string, so it will be different under the two browsers. Under IE, you can directly use the LoadXML method to parse the XML string, while under FF, you need to use the parseFromString() method of the DOMParser object, which is
var oParser=new DOMParser();
xmlDoc=oParser.parseFromString(xmlStr,"text/xml");
In order to be universal in both browsers, I thought of javascriptp's exception handling method, which is try...catch...

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


[Ctrl A Select all Note: If you need to introduce external Js, you need to refresh to execute
]

Look, whether in ie or 1400 has popped up in 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");
.0, Safari2.0
XmlDoc = (new DOMParser()).parseFromString(strXml, "text/xml");
}
return XmlDoc;
}
return Exc() ;
}

The functions are the same, and they are all designed to handle the parsing of xml strings in ie and ff. However, some people on Wuyou said that the xml string must have , but after testing, if there is xml version="1.0" encoding="gb2312"?> ;, the parsing results are inconsistent, so I did not add these characters in the example above.​
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template