注册 登录
编程论坛 Ruby论坛

[求助]亟亟等待求助dom添加两个元素子节点问题。。

shiyide 发布于 2006-09-21 17:15, 3800 次点击

请问如何使用dom对象的appendChild方法同时添加两元素子节点,并且能显示出来,用js脚本语言写
xml代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<Address>
<Custom Sex="男">
<Name>吴梦达</Name>
<E-Mail>Mengda@sina.com</E-Mail>
</Custom>
<Custom Sex="女">
<Name>白晶晶</Name>
<E-Mail>ghost@sina.com</E-Mail>
</Custom>
</Address>

要求在客户节点添加两个元素节点“公司”“联系电话”,其中元素节点“联系电话”含有“手机”与“办公电话”两个属性节点
部分js代码如下:
<html>
<head>
<title>Enter the title of your HTML document

here</title>
</head>
<body>
<p>Enter the body text of your HTML document

here</p>
<script language="javascript">
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.load("Client.xml");
var cNode;
var tNode;
var mobile;
var tel;
var childs;
var i;

cNode = xmlDoc.createNode(1,"公司","");
tNode = xmlDoc.createNode(1,"联系电话","");
mobile = xmlDoc.createNode(2,"手机","");
tel = xmlDoc.createNode(2,"办公室电话","");
childs = xmlDoc.documentElement;
childs.childNodes[0].appendChild(cNode);
childs.childNodes[0].lastChild.setAttributeNode(tel);
childs.childNodes[1].appendChild(cNode);
childs.childNodes[1].lastChild.setAttributeNode(tel);

window.alert(childs.xml);
</script>
</body>
</html>

最后跳出来的窗口总是只有最后加进去的一个元素节点,不会实现两个同时显示
请高手指导

1 回复
#2
mordew2006-09-23 18:42

<html>
<head>
<title>Aptech</title>
</head>
<body>
<script language="javascript">
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.load("Client.xml");
if(xmlDoc.parseError.errorCode != 0)
window.alert(xmlDoc.parseError.reason);
else
{
var child = xmlDoc.documentElement.childNodes[0];
while(child != null)
{
var cNode = xmlDoc.createNode(1,"公司","");
var tNode = xmlDoc.createNode(1,"联系电话","");
var mobile = xmlDoc.createNode(2,"手机","");
var tel = xmlDoc.createNode(2,"办公室电话","");
child.appendChild(cNode);
child.appendChild(tNode);
child.lastChild.setAttributeNode(mobile);
child.lastChild.setAttributeNode(tel);
child = child.nextSibling;
}
window.alert(xmlDoc.documentElement.xml);
}
</script>
</body>
</html>

1