现在的位置: 首页 > 综合 > 正文

DOM操作XML事例

2013年07月01日 ⁄ 综合 ⁄ 共 1235字 ⁄ 字号 评论关闭

<html>

<head>
<meta content="text/html" http-equiv="content-type" ; charset=gb2312>
<title>Munipulate HTML</title>
</head>
<script type="text/javascript">
//定义根结点
var root;
var xmlDoc= new ActiveXObject("Msxml2.DOMDocument");
xmlDoc.async = false;
function CreateXML()
{
    //添加文件头
    var p = xmlDoc.createProcessingInstruction("xml","version='1.0' encoding='gb2312'");
    //var p = xmlDoc.createProcessingInstruction("xml","version='1.0' encoding='gb2312'");
    xmlDoc.appendChild(p);
    //创建根结点
    root = xmlDoc.createNode(1,"book","");
    //设置根节点的属性
    var l= xmlDoc.createAttribute("level");
    l.value="2";
    root.setAttributeNode(l);
    //创建子结点Name
    var name = xmlDoc.createNode(1,"Name","");
    //指字根结点文本
    name.text ="ajax 入门教程";
    //创建子节点Price
    var Price = xmlDoc.createNode(1,"Price","");
    //指定子节点文本
    Price.text ="20";
    //创建子节点info
    var info = xmlDoc.createNode(1,"info","");
    //创建孙节点i
    var i = xmlDoc.createElement("i");
    //指定其文本
    i.text = "200";
    //添加孙节点
    info.appendChild(i);
    //添加子节点
    root.appendChild(name);
    root.appendChild(Price);
    root.appendChild(info);
    //添加根节点
    xmlDoc.appendChild(root);
    alert(root.xml);
}
</script>

<body>

<form name="buttonForm" method="post" action="">
<input  type="button" id="create" value="CreateXML" onclick="CreateXML()"  >
</form>

</body>

</html>

抱歉!评论已关闭.