当前位置: 首页 > 网络学院 > XML相关教程 > XML DOM > appendChild() 方法

XML DOM
DOM Attribute
DOM Text
DOM CDATA
DOM Comment
DOM HttpRequest
DOM ParseError
DOM 校验器
DOM 介绍
DOM 摘要
DOM 案例
DOM 节点树
DOM 访问节点树
DOM 节点信息
DOM 文档执行
DOM 节点导航

XML DOM 中的 appendChild() 方法


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-03-04   浏览: 319 ::
收藏到网摘: n/a

Definition and Usage
定义和用法

The appendChild() method adds a node after the last child node of the specified element node.
appendChild()方法的作用是:在指定元素节点的最后一个子节点之后添加一个节点。

This method returns the new child node.
这个方法将返回新的子节点。

Syntax
语法

appedChild(node)

Parameter
参数
Description
描述
node Required. The node to append
必要参数。指定需要追加的节点


In all examples, we will use the XML file books.xml, and the JavaScript function loadXMLDoc().
在所有案例中,我们将使用“book.xml”文件以及JavaScript 函数“loadXMLDoc()”。

Example 1
案例1

The following code fragment creates and appends a node to the first <book> element, and then outputs all child nodes of the first <book> element:
下面的代码片断将创建和追加一个节点到第一个<book>元素中,并输出第一个<book>元素中的所有子节点:

xmlDoc=loadXMLDoc("books.xml");
var newel=xmlDoc.createElement('edition');
var newtext=xmlDoc.createTextNode('First');
newel.appendChild(newtext);
var x=xmlDoc.getElementsByTagName('book')[0];
x.appendChild(newel);
var y=x.childNodes;
for (var i=0;i<y.length;i++) { //Display only element nodes if (y[i].nodeType==1) { document.write(y[i].nodeName); document.write("<br />"); } }

Output:
输出结果:

title
author
year
price
edition

Note: Internet Explorer will skip white-space text nodes that are generated between nodes (e.g. new-line characters), while Mozilla will not. So, in the example above, we only process element nodes (element nodes have nodeType=1).
注意:IE将跳过在节点之间产生的空格文档节点(如:换行字符),而Mozilla不会这样。在下面的案例中,我们将只处理元素节点(元素节点的nodeType=1)。

To read more about the differences between IE and Mozilla browsers, visit our Mozilla vs. IE chapter.
如果你想获取更多关于IE和Mozilla浏览器的不同,那你可以访问“Mozilla vs. IE ”这章。


Example 2
案例2

The following code creates and appends a node to all <book> elements in "books.xml":
下面的代码片断将在“books.xml”文件中创建并追加一个节点:

xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName('book');
var newel,newtext
for (i=0;i<x.length;i++) { newel=xmlDoc.createElement('edition'); newtext=xmlDoc.createTextNode('First'); newel.appendChild(newtext); x[i].appendChild(newel); }
//Output all titles and editions
var y=xmlDoc.getElementsByTagName("title");
var z=xmlDoc.getElementsByTagName("edition");
for (i=0;i<y.length;i++) { document.write(y[i].childNodes[0].nodeValue); document.write(" - Edition: "); document.write(z[i].childNodes[0].nodeValue); document.write("<br />"); }

Output:
输出结果:

Everyday Italian - Edition: First
Harry Potter - Edition: First
XQuery Kick Start - Edition: First
Learning XML - Edition: First


Try-It-Yourself Demos
自我演示

appendChild() - Append a child node to the first <book> node
appendChild() - 追加一个子节点到第一个<book>节点中

appendChild() - Append a child node to all <book> nodes
appendChild() - 追加一个子节点到所有的<book>节点中

评论 (0) All

登陆 | 还没注册?