1. 解析XML字符串
function
XMLResolve(xmlStr) {
var parseXML =
"";
if(typeof
DOMParser ==
"function") {
parseXML = function(xmlStr) {
return (new
DOMParser()).parseFromString(xmlStr,
"text/xml");
}
}
else if(typeof window.
ActiveXObject !=
'undefined' && new
Window.
ActiveXObject(
'Microsoft.XMLDOM')) {
parseXML = function(xmlStr) {
var xmlDOC = new
Window.
ActiveXObject(
"Microsoft.XMLDOM");
xmlDOC.async =
'false';
xmlDOC.loadXML(xmlStr);
return xmlDOC;
};
}
else {
throw new
Error(
"No XML parser found");
}
return parseXML(xmlStr);
}
var xml =
XMLResolve(
"<foo>XML文件<child>2333</child></foo>");
console.log(xml);
console.log(xml.documentElement.childNodes[
1].childNodes[
0]);
出现的结果:
2. 解析XML文件
function
XMLFileResolve(xmlFile) {
var xmlDoc=null;
if(window.
ActiveXObject) {
xmlDoc = new
ActiveXObject(
"Microsoft.XMLDOM");
}
else if(document.implementation && document.implementation.createDocument) {
xmlDoc = document.implementation.createDocument(
'',
'',null);
}
else {
return null;
}
if(xmlDoc!=null){
xmlDoc.async =
false;
xmlDoc.load(xmlFile);
}
return xmlDoc;
}
var file =
XMLFileResolve(
"foo.xml");
console.log(file);
执行结果如下:
个人觉得XML其实也是可以看作一个节点树的,从根结点,经过中间的节点,再到叶子节点,而且另一方面来说,XML文件和HTML文件标记语言,只是应用的范围不同而已
转载请注明原文地址: https://ju.6miu.com/read-37746.html