初学javascript,学习中用到在IE中建立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
50
51
52
53
54
55
56
57
58 |
function
XmlObject() { var
oXml = new
ActiveXObject("Microsoft.XMLDOM"); this.getXmlObj = function() { return
oXml; } this.InitXmlObj = function() { oXml = new
ActiveXObject("Microsoft.XMLDOM"); //对象 } this.isTop = function(oNode) { if
(oNode === oXml) return
true; return
false; } this.AddTextNode = function(oParent, sKey, sValue) { if
(this.isTop(oParent) == true) { //为顶级对象添加的节点不能超过一个 if
(oXml.childNodes.length > 0) { //已经存在根节点,不继续添加 return
null; } } var
oNewNode = oXml.createElement(sKey); var
oTextNode = oXml.createTextNode(sValue); oParent.appendChild(oNewNode); oNewNode.appendChild(oTextNode); return
oNewNode; } this.AddAttrNode = function(oParentNode, sNodeName, sAttr, sValue) { if
(this.isTop(oParent) == true) { //为顶级对象添加的节点不能超过一个 if
(oXml.childNodes.length > 0) { //已经存在根节点,不继续添加 return
null; } } var
oNewNode = oXml.createElement(sNodeName); oParentNode.appendChild(oNewNode); oNewNode.setAttribute(sAttr, sValue); return
oNewNode; } this.AddAttrTextNode = function(oParentNode, sNodeName, sNodeText, sAttrName, sAttrValue) { if
(this.isTop(oParentNode) == true) { //为顶级对象添加的节点不能超过一个 if
(oXml.childNodes.length > 0) { //已经存在根节点,不继续添加 return
null; } } var
oNewNode = oXml.createElement(sNodeName); var
oTextNode = oXml.createTextNode(sNodeText); oParentNode.appendChild(oNewNode); oNewNode.setAttribute(sAttrName, sAttrValue); oNewNode.appendChild(oTextNode); return
oNewNode; } this.getXmlStr = function() { return
oXml.xml; }} |
演示代码:
|
1
2
3
4
5
6
7
8
9 |
function
onXml() { var
oXmlOp = new
XmlObject(); var
oTop = oXmlOp; var
oTop = oXmlOp.AddAttrTextNode(oXmlOp.getXmlObj(), "UserInfo", "", "class", "dianxin1005"); oXmlOp.AddAttrTextNode(oTop, "Subject", "Chinese", "Score", "98"); oXmlOp.AddAttrTextNode(oTop, "Subject", "Math", "Score", "77"); oXmlOp.AddAttrTextNode(oTop, "Subject", "English", "Score", "99"); alert(oXmlOp.getXmlStr());} |
生成的XML是:
<UserInfo class="dianxin1005">
<Subject Score="98">
Chinese
</Subject>
<Subject Score="77">
Math
</Subject>
<Subject Score="99">
English
</Subject>
</UserInfo>
原文:http://www.cnblogs.com/sunsoftresearch/p/3533452.html