/**
* 得到XML文件属性的集合对象
*
@param
xmlDoc XML对象
*
@param
name 属性名称 如: user
*
@return
返回 Array 对象
* Example XML:
* <?xml version='1.0' encoding='utf-8'?>
* <ekuy>
* <user>
* <name>
* <cnname>小猪</cnname>
* </name>
* <age>27</age>
* </user>
* <user>
* <name>
* <cnname>小霞</cnname>
* </name>
* <age>26</age>
* </user>
* </ekuy>
*/
function getXMLArray(xmlDoc, name) {
var keys
=
name.split(
'
.
'
);
var node
=
xmlDoc.documentElement;
//
得到根节点
var rtn
=
new
Array();
var n
=
0
;
for
(var i
=
0
; i
<
keys.length; i
++
) {
var childs
=
node.childNodes;
//
得到子节点
var key
=
keys[i];
for
(var k
=
0
; k
<
childs.length; k
++
) {
var child
=
childs[k];
if
(child.nodeName
==
key) {
//
判断子节点是否符合
if
(i
==
keys.length
-
1
) {
rtn[n]
=
child;
n
++
;
}
else
{
node
=
child;
break
;
}
}
}
}
return
rtn;
}
/**
* 得到由getXMLArray函数得到对象中的值
*
@param
node 节点对象
*
@param
name
*
@return
返回 String
*/
function getValue(node, name) {
var keys
=
name.split(
'
.
'
);
for
(var i
=
0
; i
<
keys.length; i
++
) {
var childs
=
node.childNodes;
//
得到子节点
var key
=
keys[i];
for
(var k
=
0
; k
<
childs.length; k
++
) {
var child
=
childs[k];
if
(child.nodeName
==
key) {
//
判断子节点是否符合
if
(child.childNodes.length
==
1
) {
//
如果没有字节点,返回值
return
child.text;
}
else
{
//
还有子节点,继续分析
node
=
child;
break
;
}
}
}
}
return
""
;
}
//
测试:
var xmlDoc
=
new
ActiveXObject(
"
Microsoft.XMLDOM
"
);
xmlDoc.async
=
false
;
xmlDoc.loadXML(
"
<?xml version='1.0' encoding='utf-8'?><ekuy><user><name><cnname>小猪</cnname></name><age>27</age></user><user><name><cnname>小霞</cnname></name><age>26</age></user><user><name><cnname>小章</cnname></name><age>25</age></user></ekuy>
"
);
var list
=
getXMLArray(xmlDoc,
'
user
'
);
for
(var i
=
0
; i
<
list.length; i
++
) {
var obj
=
list[i];
document.write(getValue(obj,
'
name.cnname
'
));
document.write(getValue(obj,
'
age
'
));
document.write(
'
<br\/>
'
);
}
posted on 2006-12-25 17:12
kelven 阅读(1235)
评论(1) 编辑 收藏 所属分类:
JavaScript