<body>
<p>This example should work in all browsers.</p>
<script type="text/javascript">
function createDocument(){
if (typeof arguments.callee.activeXString != "string"){
var versions = ["MSXML2.DOMDocument.6.0", "MSXML2.DOMDocument.3.0", "MSXML2.DOMDocument"];
for (var i=0,len=versions.length; i < len; i++){
try {
var xmldom = new ActiveXObject(versions[i]);
arguments.callee.activeXString = versions[i];
return xmldom;
} catch (ex){
//skip
}
}
}
return new ActiveXObject(arguments.callee.activeXString);
}
function serializeXml(xmldom){
if (typeof XMLSerializer != "undefined"){
return (new XMLSerializer()).serializeToString(xmldom);
} else if (typeof xmldom.xml != "undefined"){
return xmldom.xml;
} else {
throw new Error("Could not serialize XML DOM.");
}
}
function parseXml(xml){
var xmldom = null;
if (typeof DOMParser != "undefined"){
xmldom = (new DOMParser()).parseFromString(xml, "text/xml");
var errors = xmldom.getElementsByTagName("parsererror");
if (errors.length){
throw new Error("XML parsing error:" + errors[0].textContent);
}
} else if (typeof ActiveXObject != "undefined"){
xmldom = createDocument();
xmldom.loadXML(xml);
if (xmldom.parseError != 0){
throw new Error("XML parsing error: " + xmldom.parseError.reason);
}
} else {
throw new Error("No XML parser available.");
}
return xmldom;
}
// 测试元素序列化
var xmldom = null;
try {
xmldom = parseXml("<root><child/></root>");
} catch (ex){
alert(ex.message);
}
alert(serializeXml(xmldom));
// 测试元素解析与
var xmldom = null;
try {
xmldom = parseXml("<root><child/></root>");
} catch (ex){
console.log(ex);
alert(ex.message);
}
alert(xmldom.documentElement.tagName); //"root"
alert(xmldom.documentElement.firstChild.tagName); //"child"
var anotherChild = xmldom.createElement("child");
xmldom.documentElement.appendChild(anotherChild);
var children = xmldom.getElementsByTagName("child");
alert(children.length); //2
try {
xmldom = parseXml("<root>");
} catch (ex){
alert("Parsing error: " + ex.message);
}
</script>
</body>
// XML 加载与解析
<body>
<p>This example will not work in Internet Explorer.</p>
<script type="text/javascript">
var parser = new DOMParser();
var xmldom = parser.parseFromString("<root><child/></root>", "text/xml");
//convert back into XML
var serializer = new XMLSerializer();
var xml = serializer.serializeToString(xmldom);
alert(xml);
</script>
</body>