Home > Article > Backend Development > XML parser - parse xml files in js
Usually we have the following requirements:
1.0 We need to read relational data in js, our first choice isxml file, but how do we read it? Here is the solution...
Step one:
We can define One method: (As long as someone calls it, it will directly return to the parser)
function parseXML(file){
try //Internet Explorer---ie浏览器的解析器创建方式如下:
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
}
catch (e) {
try //Firefox, Mozilla, Opera, etc. 火狐等浏览器的创建方式。
{
xmlDoc = document.implementation.createDocument("", "", null);
}
catch (e) {
alert(e.message);
return; //如果创建不成功,就直接返回,不往下走。
}
}
xmlDoc.async = false;
xmlDoc.load(file);
return xmlDoc; //返回创建好的解析器,传给调用者。
}Second step:
In js Call the method directly to get the parser:
<script language="JavaScript">
window.onload = function(){
var xmlDoc = parseXML("file.xml");
//调用上面我们定义的方法,给方法一个参数,参数就是你要解析的xml文件,得到这个文件的对象,也就相当于把xml文件包装成了一个document。
}
</script>The above is the detailed content of XML parser - parse xml files in js. For more information, please follow other related articles on the PHP Chinese website!