独上高楼网站
  •    你所在位置:首页 VS.netXMLXML基础教程〉XML基础教程:XML DOM 替换节点
  • XML基础教程:XML DOM 替换节点
  • 作者:佚名  文章来源:ttp://www.w3school.com.cn  发布日期:2008-03-06  浏览次数:265
  • 打印这篇文章
  • XML DOM 替换节点

    实例

    在下面的例子中,我们将使用XML文件books.xml,以及JavaScript函数loadXMLDoc()。

    替换一个节点列表中的某个节点
    本例使用replaceChild()来替换节点列表中的最后一个子节点。
    替换文本节点中的数据
    本例使用replaceData()来替换文本节点中的数据。

    替换节点列表中的某个节点

    replaceChild()方法被用来替换节点列表中的某个节点。

    下面的代码片段可创建一个新的< book>元素来替换最后一个< book>元素:

    //check if last child node is an element node
    function get_lastchild(n)
    {
    var x=n.lastChild;
    while (x.nodeType!=1)
      {
      x=x.previousSibling;
      }
    return x;
    }
    
    xmlDoc=loadXMLDoc("books.xml");
    
    var x=xmlDoc.documentElement;
    
    //create a book element, title element and a text node
    var newNode=xmlDoc.createElement("book");
    var newTitle=xmlDoc.createElement("title");
    var newText=xmlDoc.createTextNode("A Notebook");
    
    //add the text node to the title node,
    //and add the title node to the book node
    newTitle.appendChild(newText);
    newNode.appendChild(newTitle);
    
    //replace the last node with the new node
    x.replaceChild(newNode,get_lastchild(x));
    

    注释:Internet Explorer会忽略节点之间产生的空白文本节点(例如换行字符),而Mozilla不会这样。因此,在上面的例子中,get_lastchild()函数会检查参数的最后一个子节点的节点类型。

    元素节点的节点类型是1,因此假如参数中节点的最末子节点不是元素节点,那么它就会移至上一个节点,并检查此节点是否为元素节点。这个过程会持续到最后一个子节点被找到为止。通过这个办法,我们就可以在Internet Explorer 和 Mozilla中得到正确的结果了。

    替换文本节点中的数据

    replaceData()方法被用来替换文本节点中的数据。

    replaceData()方法有三个参数:

    • offset - 从何处开始替换字符。偏移量的起始值为0
    • length - 替换多少字符
    • string - 要插入的字符串

    下面的代码片段将使用"Easy"替换首个< title>元素中文本节点的开头的8个字符:

    xmlDoc=loadXMLDoc("books.xml");
    
    var x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
    
    x.replaceData(0,8,"Easy");
    
  • 打印这篇文章
  • 与本文主题相关的文章
  • 返回首页