js高程读书笔记 第18章 JavaScript与XML

[TOC]

本章内容

  • 检测浏览器对XML DOM的支持
  • 理解JavaScript中XPath
  • 使用XSLT处理器

浏览器对XML DOM的支持

DOM2级核心

1
var xmldom = document.implementation.createDocument(namespaceUri, root, doctype);

DOMParser类型

1
2
var parser = new DOMParser();
var xmldom = parser.parseFromString("<root><child/></root>", "text/xml");

XMLSerializer类型

提供了和DOMParser相反的功能,将DOM文档序列化为XML字符串

1
2
3
var serializer = new XMLSerializer();
var xml = serializer.serializeToString(xmldom);
coonsole.log(xml);

IE8及之前版本中的XML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
function createDocument(){
var versions = ["MSXML2.DOMDocument.6.0", "MSXML2.DOMDocument.3.0",
"MSXML2.DOMDocument"],
i, len;


for (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);
}


var xmldom = createDocument();
xmldom.async = true;

xmldom.onreadystatechange = function(){
if (xmldom.readyState == 4){
if (xmldom.parseError != 0){
alert("An error occurred:\nError Code: "
+ xmldom.parseError.errorCode + "\n"
+ "Line: " + xmldom.parseError.line + "\n"
+ "Line Pos: " + xmldom.parseError.linepos + "\n"
+ "Reason: " + xmldom.parseError.reason);
} else {

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

alert(xmldom.xml);
}
}
};

xmldom.load("example.xml");

跨浏览器处理XML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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;
}

序列化xml

1
2
3
4
5
6
7
8
9
10
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.");
}
}

xpath

xml中节点的选择方法