XML DOM教程[转]

XML DOM教程 *

XML文档对象模型(XML Document Object Model,即:XML DOM)定义了访问和操作XML文档的标准方式。
DOM在一个XML文档中是以一个树形结构存在的(不是一个节点树),其中包含了元素、属性以及以节点形式定义的文本。

XML DOM 对象参考

可以找到完整的DOM参考,内容有:所有对象以及它们的属性和方法

XML DOM 参考

XML DOM 实例

通过我们的编辑器学习50个实例!

前往实例库

XML DOM介绍
w3pop.com / 2006-09-19

p.gif XML DOM 节点 n.gif

The XML Document Object Model defines a standard way for accessing and manipulating XML documents.
XML文件对象模型(XML DOM)定义了一个访问和操作XML文档的标准方式。


What You Should Already Know
你应该已经掌握的知识

Before you continue you should have a basic understanding of the following:
在你继续看下去之前,你得基本了解一些下面所要说明的东西:

  • HTML / XHTML
  • JavaScript
  • XML

如想进一步了解,请先看一下我们的教程:教程首页

What is the DOM?
到底什么是DOM?

"The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document."
W3C文件对象模型(DOM)可以看作是一个平台或语言中立的(language-neutral)界面,它允许程序和脚本动态的访问以及更新文档的内容、结构、脚本程序。

The W3C DOM provides a standard set of objects for HTML and XML documents, and a standard interface for accessing and manipulating them.
W3C DOM提供了一组描述HTML及XML文件的标准对象和一个用来访问和操作这类文件的标准界面。

The W3C DOM is separated into different parts (Core, XML, and HTML) and different levels (DOM Level 1/2/3):
DOM分为3部分(Core核心, XML, 和 HTML)及不同等级(DOM 等级 1/2/3)。

  • Core DOM - defines a standard set of objects for any structured document
    核心DOM-定义了一组可用于任何结构文档的标准对象。
  • XML DOM - defines a standard set of objects for XML documents
    XML DOM-定义了一组XML文件的标准对象。
  • HTML DOM - defines a standard set of objects for HTML documents
    HTML DOM-定义了一组HTML文件的标准对象。

What is the XML DOM?
何谓XML DOM?

  • The XML DOM is the Document Object Model for XML 
    XML DOM是XML的文件对象模型
  • The XML DOM is platform- and language-independent 
    XML DOM是平台和语言独立体
  • The XML DOM defines a standard set of objects for XML
    XML DOM定义了一组XML标准对象
  • The XML DOM defines a standard way to access XML documents
    XML DOM定义了访问XML文件的标准方式
  • The XML DOM defines a standard way to manipulate XML documents
    XML DOM定义了控制XML文件的标准方式
  • The XML DOM is a W3C standard
    XML DOM是W3C标准

The DOM views XML documents as a tree-structure. All elements; their containing text and their attributes, can be accessed through the DOM tree. Their contents can be modified or deleted, and new elements can be created. The elements, their text, and their attributes are all known as nodes.
XML DOM是将XML文档以元素(这里的元素是包含在其他文档中的)的树形结构来浏览的。所有元素所包含的文本以及属性,都能通过DOM树来访问。它们的内容可以被修改或删除,新元素也可以通过DOM重新创建。这些元素的文本及其属性就是我们所知道的节点(node)。

XML DOM 节点
w3pop.com / 2006-09-21

p.gifXML DOM介绍 DOM Node 列 n.gif

The DOM Structure Model
XMLDOM 结构模型

The DOM treats the XML document as a tree-structure. Each element, attribute, and text in the XML document represents a node in the tree.
DOM把XML文件当作一种树形结构。每个元素,属性以及 XML文件中的文本都可以看成树上的节点。

The terms "parent" and "child" are used to describe the relationships between nodes. Some nodes may have child nodes, while other nodes do not have children (leaf nodes).
术语"parent" 和"child"是用于描述节点间关系的。一些节点类型可能是子节点,而其他的节点类型(other node type)却不允许有子节点。

Because the XML data is structured in a tree form, it can be traversed without knowing the exact structure of the tree and without knowing the type of data contained within.
因为XML数据是以树形结构构造出来的,所以它不需要知道精确的树形构造和所包含的数据类型就能通过。


DOM Node Example
DOM节点实例

来看看下面的XML文件:books.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">Xquery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

Notice that the root element in the XML document above is named <bookstore>. All other elements in the document are contained within <bookstore>.
可以注意到上面这个XML文档中的根元素命名为<bookstore>。所有其它文档中的元素都包含在<bookstore>里

The <bookstore> element represents the root node of the DOM tree.
<bookstore>元素代表了这棵DOM树的根节点

The root node <bookstore> holds four <book> child nodes.
根节点<bookstore>包含了四个子节点<book>

The first <book> child node also holds four children: <title>, <author>, <year>, and <price>, which contains one text node each, "Everyday Italian", "Giada De Laurentiis", "2005", and "30.00".
第一个<book>子节点还包含了四个子节点:<title>,<author>, <year>, 和 <price>,它们的文字节点分别为"Everyday Italian", "Giada De Laurentiis", "2005", 和 "30.00"

IMPORTANT! Text is always stored in text nodes. A common error in DOM processing is to navigate to an element node and expect it to contain the text. However, even the simplest element node has a text node under it. For example, in <year>2005</year>, there is an element node (year), and a text node under it, which contains the text (2005).
重要信息!文字必须保存在文字节点内。比如,在<year>2005</year>中,有个元素节点(year)有个文字节点在它的下面,里面的文字为(2005)

The following image illustrates a fragment of the DOM node tree from the XML document above:
下面的个图片说明了上面XML文档的DOM节点树

DOM node tree

For a complete reference of all the node types and which children they may have, go to our Node types reference.
想要查看所有节点类型以及它们所能包含的子节点,可以前往我们的节点类型参考。

DOM Node 列
w3pop.com / 2006-09-21

p.gifXML DOM 节点 DOM 解析 n.gif

DOM Node List and NamedNodeMap
DOM节点列表对象和NamedNodeMap[指定节点映射]

This chapter explains what a NodeList is, and what a NamedNodeMap is. It also explains the differences between them.
通过本章的学习,你将会明白什么是节点列表,什么是NamedNodeMap[指定节点映射],以及它们之间存在着哪些不同。


DOM Node List
DOM节点列表对象

When using properties or methods like childNodes or getElementsByTagName(), we receive a NodeList object.
当使用诸如childNodes 或者 getElementsByTagName()这样的属性或方法时,我们将获取一个NodeList[节点列表]对象。

A NodeList object represents an ordered list of nodes.
一个NodeList[节点列表]表示一个完整规则的节点列表。

The nodes in the NodeList can be accessed through their index number (starting from 0).
NodeList[节点列表]中的节点可以通过它们的索引数字(从0开始)访问。

Note: In a NodeList, the nodes are returned in the order in which they are specified in the XML.
注意:在一个NodeList[节点列表]中,节点是按照我们在XML中指定的顺序返回的。

来看看这个XML文件: books.xml

We will now create a node list of all the <title> elements in "books.xml", by using the getElementsByTagName("title") method. The following image represents the node list returned:
我们将使用getElementsByTagName("title")方法在“book.xml”文件中创建所有的<title>元素节点列表。下面的图片展示了这个返回的节点列表:

DOM node list

The following code fragment gets the text from the first <title> element:
下面这个代码片段将获取来自于第一个<title>元素的文本:

getElementsByTagName("title")[0].childNodes[0].nodeValue

Output:
输出结果:

Everyday Italian


Get the Length of a Node List
获取节点列表长度

The node list keeps itself up-to-date. If an element is deleted or added, in the node list or the XML document, the list is automatically updated.
节点列表将会不断地进行自我更新。如果节点列表或XML文档中的一个元素被添加或是删除,那么列表将自动更新。

The node list has a useful property: length. The length property returns the number of nodes in a node list.
节点列表拥有一个非常实用的属性:length[长度]。length[长度]属性返回了节点列表中节点的数量。

The following code fragment gets the number of <title> elements in "books.xml":
下面这个代码片段将获取“books.xml”文件中的<title>元素的数量:

getElementsByTagName('title').length

Output:
输出结果:

4

When you know the length of a node list, you can easily loop through it and extract the values you want.
当我们已经知道了一个节点列表长度时,你可以非常方便的对它执行循环语句并从中提取你想要的值。

The following code fragment loops through all <title> elements and prints their values:
下面这个代码片段将对<title>元素执行循环语句并输出它们的值:

//the x variable will hold a NodeList
var x=getElementsByTagName('title')
for (i=0;i<x.length;i++)
{
document.write(x[i].childNodes[0].nodeValue)
document.write("<br />")
}

Output:
输出结果:

Everyday Italian
Harry Potter
XQuery Kick Start
Learning XML


DOM NamedNodeMap
DOM 指定节点映射

When using the attributes property on an element, we receive a NamedNodeMap object.
当对一个元素使用attribute属性时,我们将获取一个NamedNodeMap[指定节点映射]对象。

A NamedNodeMap object represents an unordered list of attribute nodes.
一个NamedNodeMap[指定节点映射]对象代表一个无序的节点列表。

The nodes in the NamedNodeMap can be accessed through their name.
NamedNodeMap[指定节点映射]对象中的节点可以通过它们的名称进行访问。

Note: In a NamedNodeMap, the nodes are not returned in any particular order.
注意:在一个NamedNodeMap[指定节点映射]对象中,节点不会以任何一种特定的顺序返回。


Get the Length of a NamedNodeMap
获取一个NamedNodeMap[指定节点映射]对象的长度

The NamedNodeMap keeps itself up-to-date. If an element is deleted or added, in the node list or the XML document, the list is automatically updated.
NamedNodeMap[指定节点映射]对象将会不断地进行自我更新。如果节点列表或XML文档中的一个元素被添加或是删除,那么列表将自动更新。

The NamedNodeMap also has a length property. The length property returns the number of nodes in the list.
NamedNodeMap[指定节点映射]对象也包含一个length[长度]属性。length[长度]属性将返回列表中节点的数量。

来看看下面这个XML文件:books.xml

The following code fragment gets the number of attributes in the first <title> element in "books.xml":
下面这个代码片段将获取来自于第一个<title>元素的属性数量:

getElementsByTagName('title')[0].attributes.length

Output:
输出结果:

1


Get an Item's Value in a NamedNodeMap
获取一个NamedNodeMap[指定节点映射]的项的值

The getNamedItem() method of the NamedNodeMap object can be used to retrieve a specified node.
NamedNodeMap[指定节点映射]对象中的getNamedItem()方法可以用于获取一个指定的节点。

The following code fragment shows how to print the value of the "category" attribute in each <book> element":
下面这段代码片断将展示如何输出每个<book>元素中“category”属性的值:

xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName("book");
for(i=0;i<x.length;i++)
{
//the attlist variable will hold a NamedNodeMap
var attlist=x.item(i).attributes;
var att=attlist.getNamedItem("category");
document.write(att.value + "<br />")
}

Output:
输出结果:

COOKING
CHILDREN
WEB
WEB

DOM 解析
w3pop.com / 2006-09-21

p.gifDOM Node 列 DOM Traverse Nodes n.gif

To read and update, create and manipulate an XML document, you will need an XML parser.
你需要通过一个XML解析器来阅读、更新、创建和操作一份XML文件。


Examples
实例

Parse an XML file - Crossbrowser example
XML文件解析– Crossbrowser举例
This example is a cross-browser example that loads an existing XML document ("note.xml") into the XML parser.
这是一个关于把一个现有的XML文件("note.xml")加载到XML解析器中去的cross-browser实例。

Parse an XML string - Crossbrowser example
XML 字符串解析 – Crossbrowser举例
This example is a cross-browser example on how to load and parse an XML string.
这是一个如何加载并解析XML字符串的cross-browser实例。


Parsing the XML DOM
解析XML DOM

To manipulate an XML document, you need an XML parser. The parser loads the document into your computer's memory. Once the document is loaded, its data can be manipulated using the DOM. The DOM treats the XML document as a tree.
要熟练操作XML文件,你需要一个XML解析器。此解析器会加载文件到你计算机的存储器里。一旦文件被加载,通过DOM就可以对它的数据进行。DOM是将XML文件以树状结构来看的。

There are some differences between Microsoft's XML parser and the XML parser used in Mozilla browsers. In this tutorial we will show you how to create cross browser scripts that will work in both Internet Explorer and Mozilla browsers.
微软的XML解析器与用于Mozilla浏览器的XML解析器有点不一样。在这份教程中我们会说明如何在IE和Mozilla中创建cross browser脚本程序。


Microsoft's XML Parser
微软XML解析器

Microsoft's XML parser is a COM component that comes with Internet Explorer 5 and higher. Once you have installed Internet Explorer, the parser is available to scripts.
微软的XML解析器是和IE5以及更高版本浏览器合在一起的COM组件;一旦你安装了IE,这个解析器对脚本程序就开始起作用了。

Microsoft's XML parser supports all the necessary functions to traverse the node tree, access the nodes and their attribute values, insert and delete nodes, and convert the node tree back to XML.
微软的XML解析器支持所有可以贯穿节点树的必要函数并访问这些节点以及属性值,插入或删除节点,或者重新把节点树转换为XML文件。

To create an instance of Microsoft's XML parser, use the following code:
要创建一个微软XML解析器,则需要用到下面的代码:

JavaScript:

var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");

VBScript:

set xmlDoc=CreateObject("Microsoft.XMLDOM")

ASP:

set xmlDoc=Server.CreateObject("Microsoft.XMLDOM")

The following code fragment loads an existing XML document ("note.xml") into Microsoft's XML parser:
下面的代码片断将一个现有的XML文件("note.xml")加载到微软XML文件:

var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.load("note.xml");

The first line of the script above creates an instance of the XML parser. The second line turns off asynchronized loading, to make sure that the parser will not continue execution of the script before the document is fully loaded. The third line tells the parser to load an XML document called "note.xml".
上面第一行的脚本程序创建了一个XML解析器的实例。第二行取消了同步加载,以保证文件在完全加载之前,避免解析器继续执行脚本程序。第三行语句制定解析器加载一个名为“note.xml”的XML文件


XML Parser in Mozilla, Firefox, and Opera
Mozilla, Firefox, 和Opera中的 XML解析器

Mozilla's XML parser supports all the necessary functions to traverse the node tree, access the nodes and their attribute values, insert and delete nodes, and convert the node tree back to XML.
Mozilla的 XML解析器支持所有贯穿整个节点树的必要函数,使其访问节点及节点属性,插入或删除节点以及把节点树重新转换为XML文件。

To create an instance of the XML parser in Mozilla browsers, use the following code:
如要创建在Mozilla浏览器中创建一个XML解析器,就要用到以下代码:

JavaScript:

var xmlDoc=document.implementation.createDocument("ns","root",null);

The first parameter, ns, defines the namespace used for the XML document. The second parameter, root, is the XML root element in the XML file. The third parameter, null, is always null because it is not implemented yet.
第一个参数ns定义了用于XML文件的命名空间。第二个参数root是XML文件的XML根元素。因为第三个参数null是空值,所以它不被执行。

The following code fragment loads an existing XML document ("note.xml") into Mozillas' XML parser:
下面的代码片断在Mozillas的XML解析器中加载了一个现存的XML文件("note.xml") 。

var xmlDoc=document.implementation.createDocument("","",null);
xmlDoc.load("note.xml");

The first line of the script above creates an instance of the XML parser. The second line tells the parser to load an XML document called "note.xml".
上面的第一行脚本程序创建了一个XML解析器的实例。第二行说明的是加载XML文件的解析器称为"note.xml"。


Parsing an XML File - A Cross browser Example
解析XML 文件- Cross browser 举例

The following example is a cross browser example that loads an existing XML document ("note.xml") into the XML parser:
下面是把现有XML文件("note.xml")加载到XML解析器的cross browser的实例:

<html>
<head>
<script type="text/javascript">

var xmlDoc;
function loadXML()
{
// code for IE
if (window.ActiveXObject)
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load("note.xml");
getmessage();
}
// code for Mozilla, Firefox, Opera, etc.
else if (document.implementation &&
document.implementation.createDocument)
{
xmlDoc=document.implementation.createDocument("","",null);
xmlDoc.load("note.xml");
xmlDoc.οnlοad=getmessage;
}
else
{
alert('Your browser cannot handle this script');
}
}
function getmessage()
{
document.getElementById("to").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
document.getElementById("from").innerHTML=
xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
document.getElementById("message").innerHTML=
xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
}

</script>
</head>
<body οnlοad="loadXML()">
<h1>W3Schools Internal Note</h1>
<p><b>To:</b> <span id="to"></span><br />

<b>From:</b> <span id="from"></span><br />
<b>Message:</b> <span id="message"></span>

</p>
</body>
</html>

Output:输出:

W3Schools Internal Note

To: Tove
From: Jani
Message: Don't forget me this weekend!



Important Note
重要节点

To extract the text (Jani) from an XML element like: <from>Jani</from>, the correct syntax is:
从XML元素中截取文本(Jani),(如:<from>Jani</from>),正确语法是:

getElementsByTagName("from")[0].childNodes[0].nodeValue

IMPORTANT: getElementsByTagName returns an array of nodes. The array contains all elements with the specified name within the XML document. In this case there is only one "from" element, but you still have to specify the array index ( [0] ).
重点:getElementsByTagName会将节点以一个数组的形式输出。这个数组包括了所有的元素(这些元素都是位于XML文件内的,且它们的名称是在“getElementsByTagName”后面的括号中指定的)。在这个例子里,尽管在这个例子里,它只指明了仅含有名称“from”的元素,但是你还是需要指定数组索引(array index)“[0]”。


Parsing an XML String - A Cross browser Example
解析XML字符串- Cross browser实例

The following code is a cross-browser example on how to load and parse an XML string:
下面是关于如何加载和解析XML字符串的cross-browser实例。

<html>
<body>
<script type="text/javascript">
var text="<note>";
text=text+"<to>Tove</to>";
text=text+"<from>Jani</from>";
text=text+"<heading>Reminder</heading>";
text=text+"<body>Don't forget me this weekend!</body>";
text=text+"</note>";
// code for IE
if (window.ActiveXObject)
{
var doc=new ActiveXObject("Microsoft.XMLDOM");
doc.async="false";
doc.loadXML(text);
}
// code for Mozilla, Firefox, Opera, etc.
else
{
var parser=new DOMParser();
var doc=parser.parseFromString(text,"text/xml");
}
// documentElement always represents the root node
var x=doc.documentElement;
document.write("Text of first child element: ");
document.write(x.childNodes[0].childNodes[0].nodeValue);
document.write("<br />");
document.write("Text of second child element: ");
document.write(x.childNodes[1].childNodes[0].nodeValue);

</script>
</body>
</html>

Output:
输出:

Text of first child element: Tove
Text of second child element: Jani

Note: Internet Explorer uses the loadXML() method to parse an XML string, while Mozilla browsers uses the DOMParser object.
注意:IE是通过loadXML() method来解析XML字符串的,而Mozilla浏览器则是使用DOMParser对象来解析的。

DOM Traverse Nodes
w3pop.com / 2006-09-21

p.gifDOM 解析 DOM Mozilla vs IE n.gif

Examples
实例

Traverse node tree
横节点树
This example shows how to loop through all child nodes of <note>, and print the node name and the node value.
这个例子说明了如何循环所有的“note”子节点,并且打印节点名称和节点值。


Traversing the Node-tree
穿越节点树(Node-tree)

Often you will need to loop through elements in an XML document or string.
你可能经常需要循环(loop)XML文件或字符串中的元素。

The example below loops through all child nodes of <note>, and prints the node name and the node value of each node:
下面的例子说明了如何循环“note”子节点,并打印节点名称和节点值:

<html>
<body>
<script type="text/javascript">
var text="<note>";
text=text+"<to>Tove</to>";
text=text+"<from>Jani</from>";
text=text+"<heading>Reminder</heading>";
text=text+"<body>Don't forget me this weekend!</body>";
text=text+"</note>";
// code for IE
if (window.ActiveXObject)
{
var doc=new ActiveXObject("Microsoft.XMLDOM");
doc.async="false";
doc.loadXML(text);
}
// code for Mozilla, Firefox, Opera, etc.
else
{
var parser=new DOMParser();
var doc=parser.parseFromString(text,"text/xml");
}
// documentElement always represents the root node
var x=doc.documentElement;
for (i=0;i<x.childNodes.length;i++)
{
document.write(x.childNodes[i].nodeName);
document.write("=");
document.write(x.childNodes[i].childNodes[0].nodeValue);
document.write("<br />");
}
</script>
</body>
</html>

Output:
输出:

to=Tove
from=Jani
heading=Reminder
body=Don't forget me this weekend!

DOM Mozilla vs IE
w3pop.com / 2006-09-21

p.gifDOM Traverse Nodes DOM 获取 Nodes n.gif

Browser-differences in DOM Parsing
不同浏览器对DOM解析的不同

Both Mozilla and Internet Explorer supports W3C's DOM specification.
Mozilla 和 IE 都支持W3C's DOM规范。

However, there are still differences between Internet Explorer's DOM and Mozilla's DOM. The most important difference is how they handle white-space text nodes. When XML generates, it often contains white-spaces between the nodes. Internet Explorer, when using node.childNodes[], will NOT contain these white-space nodes. In Mozilla, those nodes will be in the array.
然而,IE 对 DOM 的处理 和 Mozilla 对 DOM 的处理方式之间仍然是存在差异的。最大的不同就是它们在空格文本节点处理上的差异。当生成XML时,它通常会在节点之间包含空格。在IE中,我们可以通过使用“node.childNodes[]”去掉这些空格。在Mozilla中,这些节点将位于数组中。

来看看下面的这个XML文件:books.xml

The following code fragment alerts how many child nodes the root element have:
下面的代码片断将会提示你在根元素中包含多少个子节点:

xmlDoc.load("books.xml");
var x=xmlDoc.documentElement.childNodes;
alert(x.length)
for (i=0;i<x.length;i++)
{
document.write(x[i].nodeType);
document.write("<br />");
}

自己尝试一下吧

Internet Explorer will skip the white-space text nodes that are generated between nodes (e.g. new line characters), while Mozilla will not. So, in the example above, Mozilla browsers will alert 9 child nodes, while Internet Explorer will alert 4.
IE 将会跳过在节点之间生成的空格文本节点(例如:新行符),然后Mozilla并不会这样。在上述的案例中,Mozilla浏览器会提示9个子节点,但是IE只会提示4个。

To iterate through the child nodes and disregard those text nodes, you can check the node type. An element node has type 1, a text node has type 3, and a comment node has type 8. To skip text nodes, you can process only nodes that are not of node type 3 (text nodes) and node type 8 (comment nodes):
通过对子节点进行重申以及忽略这些子节点,你可以检验节点类型。元素节点为“类型1”,文本节点为“类型3”,注释节点为“类型8”;你可以通过仅处理除文本节点(类型3)和注释节点(类型8)的节点来跳过文本节点,具体如下:

xmlDoc.load("books.xml");
var x=xmlDoc.documentElement.childNodes;
for (var i=0;i<x.length;i++)
{
if ((x[i].nodeType!=3)&&(x[i].nodeType!=8))
{
//Do not process text nodes or comment nodes
document.write(x[i].nodeName);
document.write("<br />");
}
}

自己尝试一下吧

The best way to only process element nodes is to iterate through the child nodes and only process those with a node type of 1:
仅对元素节点进行处理的最好方法就是通过重申子节点并仅对“类型1”的节点进行处理,具体如下:

xmlDoc.load("books.xml");
var x=xmlDoc.documentElement.childNodes;
for (var i=0;i<x.length;i++)
{
if (x[i].nodeType==1)
{
//Process only element nodes
document.write(x[i].nodeName);
document.write("<br />");
}
}

如果你想查看完整的节点类型参数以及它们的子节点参数,可以查阅我们的节点类型参数

DOM 获取 Nodes
w3pop.com / 2006-09-21

p.gifDOM Mozilla vs IE DOM 设置 Nodes n.gif

Examples
实例

In the examples below, we will use the XML file books.xml, and the JavaScript function loadXMLDoc().
在下面的例子中,我们会用到这个XML文件:“books.xml”,以及JavaScript 函数“loadXMLDoc()”。

获取一个元素值
This example uses the getElementsByTagname() method to get the values of all "title" elements in "book.xml"
此例通过getElementsByTagname()方法来获得"book.xml"中的所有"title"元素值。

获取一个属性值
This example uses the getAttribute() method to get the values of all "category" attributes in "book.xml".
此例通过getAttribute()方法来获得"book.xml"中所有"category"的属性值。

获取一个项的值
This example uses the getNamedItem() method to get the values of all "category" attributes in "book.xml".
此例通过getNamedItem()方法获得"book.xml"文件中所有的"category"属性值。


Get an Element's Value
得到一个元素值

The getElementsByTagname() method returns a nodelist that contains all elements with the specified tag name in the same order as they appear in the source document.
getElementsByTagname() 方法输出一份包含所有指定标签名称元素的节点列表(nodelist),这些节点列表中,所有元素指定的标签名的排列顺序与它们在源文件中一样。

The following code fragment prints the values of all "title" elements in "book.xml":
下面的代码片断显示了"book.xml"中的所有"title"元素值:

xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName('title');
for (i=0;i<x.length;i++)
  {
  document.write(x[i].childNodes[0].nodeValue)
  document.write("<br />")
  }

Output:
输出:

Everyday Italian
Harry Potter
XQuery Kick Start
Learning XML


Get an Attribute's Value
获得一个属性值

The getAttribute() method can be used to display the value of an attribute.
getAttribute() method的作用是显示属性值。

The following code fragment prints the values of all "category" attributes in "book.xml":
接下来的代码片断显示了"book.xml"中的所有"category"属性值:

xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName('book');
for (i=0;i<x.length;i++)
{
document.write(x[i].getAttribute('category'));
document.write("<br />");
}

Output:
输出:

COOKING
CHILDREN
WEB
WEB


Get an Item's Value
得到一个项目(Item)值

The getNamedItem() method can be used to retrieve a specified node.
getNamedItem() 方法的作用是获取指定代码。

The following code fragment shows how to print the value of the "category" attribute in each <book> element":
接下来的代码片断说明的是如何在每个<book>元素中显示"category"的属性值:

xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName("book");
for(i=0;i<x.length;i++)
  {
  var attlist=x.item(i).attributes;
  var att=attlist.getNamedItem("category");
  document.write(att.value + "<br />")
  }

Output:
输出结果:

COOKING
CHILDREN
WEB
WEB

DOM 设置 Nodes
w3pop.com / 2006-09-21

p.gifDOM 获取 Nodes XML DOM 删除 Nodes n.gif

Examples
实例

In the examples below, we will use the XML file books.xml, and the JavaScript function loadXMLDoc().
在下面的例子中,我们会用到这个XML文件:books.xml,以及JavaScript 函数“loadXMLDoc()”。

设置一个新的属性和属性值
This example uses setAttribute() to set a new attribute/attribute value.
通过setAttribute() 方法,此实例设置了一个新属性/属性值。

创建一个新属性节点
This example uses createAttribute() to create a new attribute node, and setAttributeNode() to insert it to an element.
通过createAttribute() 方法,此实例制造了一个新属性节点,并且setAttributeNode() 增加了一个新元素。!!!!

改变属性值
This example uses the setAttribute() method to change the value of an existing attribute.
通过setAttribute() 方法,此实例改变了现有属性值。

改变一个项目的值
This 恶性ample shows how to change a item's value.
这个案例将展示如何改变一个项目的值。

This example uses the getNamedItem() method to change the value of an existing attribute.
通过getNamedItem() 方法,这个实例改变了现有属性值。


Set a New Attribute and Attribute Value
设置一个新属性和属性值

The setAttribute() method can be used to change the value of an existing attribute, or to create a new attribute/attribute value for an element.
setAttribute()的作用:改变元素现有的属性值,或创建一个新的属性/属性值。

The following code fragment adds a new attribute/attribute value to each <book> element:
下面的代码片断在每个<book>元素中添加了一个新的属性/属性值:

xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName("book");
for(i=0;i<x.length;i++)
{
x.item(i).setAttribute("edition","first");
}


Another Way to Create a New Attribute
其他设置新属性的方法!!!

The createAttribute() is used to create a new attribute node.
createAttribute() 的作用:制造一个新属性节点!!!!

The following code fragment uses createAttribute() to create a new attribute node, and setAttributeNode() to insert it to an element.:
下面的代码片断使用createAttribute()方法创建了一个新的属性节点,并通过setAttributeNode()方法将它插入到一个元素中:

xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName('book');
var newatt;
for (i=0;i<x.length;i++)
{
newatt=xmlDoc.createAttribute("edition").value="first";
x[i].setAttributeNode(newatt);
}


Change an Attribute Value
改变一个属性值

The setAttribute() method can be used to change the value of an existing attribute, or to create a new attribute/attribute value for an element.
setAttribute() method作用:改变元素现有的属性值,或创建一个新的属性/属性值。

The following code fragment changes the value of the existing "category" attribute (in each <book> element):
下面的代码片断把现有"category"属性值(在每个<book>元素中)设置成新值:"BESTSELLER":

xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName("book");
for(i=0;i<x.length;i++)
{
x.item(i).setAttribute("category","bestseller");
}


Change an Item's Value
改变一个项目(Item)的值

The getNamedItem() method can be used to change the value of an existing item.
getNamedItem() method作用:改变现有项目值!!!

The following code fragment also changes the value of the existing "category" attribute (in each <book> element):
下面的代码片断把每个<book>元素中的"category" 属性值转换成了"BESTSELLER":

xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName("book");
for(i=0;i<x.length;i++)
{
var att=x.item(i).attributes.getNamedItem("category");
att.value="bestseller";
}

XML DOM 删除 Nodes
w3pop.com / 2006-09-21

p.gifDOM 设置 Nodes DOM 更换 Nodes n.gif

Examples
实例

In the examples below, we will use the XML file books.xml, and the JavaScript function loadXMLDoc().
在下面的例子中,我们需要用到此XML文件:books.xml和Java脚本函数 loadXMLDoc().

删除一个元素
This example uses removeChild() to remove the last <book> element from the loaded XML.
这个实例通过removeChild() 方法从已加载的XML文件里删除未尾的<book〉元素。

从一个文本节点中删除文本
This example uses deleteData() to remove text from a text node in the loaded XML.
此实例通过deleteData() 方法从已加载的XML文件元素中删除文档。

删除一个属性
This example uses removeAttribute() to remove all "category" attributes from the loaded XML.
此实例通过removeAttribute() method从已加载的XML文件中删除所有"category"属性。

使用 removeAttributeNode()
This example uses removeAttributeNode() to remove all "category" attributes from the loaded XML.
此实例通过removeAttributeNode() method 从已加载的XML文件中删除所有"category"属性。


Remove an Element
删除一个元素

The removeChild() method can be used to remove a specified node.
removeChild() method的作用是删除指定节点。

The following code fragment will remove the last <book> element from the loaded xml:
下面一份代码片断会从加载的XML文件中删除未尾的<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;
x.removeChild(get_lastchild(x));

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, the get_lastchild() function checks the node type of the last child node of the parameter.
注意:IE浏览器将跳过在节点中产生的空格文本节点(如:跳过新一行字符);然而Mozilla浏览器却不会。因此,在上述案例中,需要使用get_lastchild()函数检验参数中最后一个子节点的节点类型。

Element nodes has a nodeType of 1, so if not the last child of the node in the parameter is an element node, it moves to the previous node, and checks if this node is an element node. This continues until the last child node (which must be an element node) is found. This way, the result will be correct in both Internet Explorer and Mozilla.
元素节点的节点类型为1,因此,如果参数中的最后一个子节点不是一个元素节点,那么它将继续向上一个节点移动,检查这个节点是不是一个元素节点,直到第一次发现这个元素节点为止。通过使用这个方法,可以同时在IE浏览器和Mozilla浏览器中显示正确的结果。


Remove Text From an Element
从元素中删除文本

The deleteData() method is used to remove data from a text node.
deleteData()的作用是从文本节点中删除指定范围的字符。

The deleteData() method has two parameters:
deleteData()含有2个参数。

  • offset - Where to begin removing characters. Offset value starts at zero
    开始端(offset)- 从哪儿开始删除字符。开始端的值从0开始。
  • count - How many characters to delete
    计数(count)- 需要删除多少字符

The following code fragment will remove the first nine characters from the first <title> element in the loaded XML:
接下来的代码片断会从已加载的XML文件的第一个<title>元素中删除第一行字符:

xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.deleteData(0,9);
 

Remove an Attribute
删除一条属性

The removeAttribute() method is used to remove an attribute node.
removeAttribute()的作用是删除一条属性。

The following code fragment will remove all "category" attributes in each <book> element:
下面的代码片段会从已加载的XML文件中删除所有的"category"属性。

xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName('book');
for(i=0;i<x.length;i++)
{
x.item(i).removeAttribute('category');
}
 

removeAttributeNode()

The removeAttributeNode() method is used to remove an attribute node.
removeAttributeNode()的作用是输出属性。

The following code fragment will remove all "category" attributes in each <book> element:
下面的代码片断会从已加载的XML文件中删除所有"category"属性。

xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName('book');
for(i=0;i<x.length;i++)
{
attnode=x.item(i).getAttributeNode("category")
old_att=x.item(i).removeAttributeNode(attnode);
document.write("Removed attribute: " + old_att.name + "<br />");
}

Output:
输出结果:

Removed attribute: category
Removed attribute: category
Removed attribute: category
Removed attribute: category

DOM 更换 Nodes
w3pop.com / 2006-09-21

p.gifXML DOM 删除 Nodes DOM 建立 Nodes n.gif

Examples
案例

In the examples below, we will use the XML file books.xml, and the JavaScript function loadXMLDoc().
在下面的例子中,我们需要用到此XML文件:books.xml和Java脚本函数 loadXMLDoc()

替换nodelist[节点列表]中的一个节点
This example uses replaceChild() to replace the last child in a node list.
这个案例将使用replaceChild()来替换一个节点列表中的最后一个子节点。

替换一个文本节点中的数据
This example uses replaceData() to replace data in a text node.
这个案例将使用replaceData()来替换一个文本节点中的数据。


Replace a Node in a Node List
替换一个节点列表中的一个节点

The replaceChild() method is used to replace a node in a node list.
replaceChild()方法的作用是:替换节点列表中的一个节点。

The following code fragment creates a new <book> element that will replace the last <book> element:
下面的代码片断将创建一个全新的<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));

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, the get_lastchild() function checks the node type of the last child node of the parameter.
注意:IE浏览器将跳过在节点中产生的空格文本节点(如:跳过新一行字符);然而Mozilla浏览器却不会。因此,在上述案例中,需要使用get_lastchild()函数检验参数中最后一个子节点的节点类型。

Element nodes has a nodeType of 1, so if not the last child of the node in the parameter is an element node, it moves to the previous node, and checks if this node is an element node. This continues until the last child node (which must be an element node) is found. This way, the result will be correct in both Internet Explorer and Mozilla.
元素节点的节点类型为1,因此,如果参数中的最后一个子节点不是一个元素节点,那么它将继续向上一个节点移动,检查这个节点是不是一个元素节点,直到第一次发现这个元素节点为止。通过使用这个方法,可以同时在IE浏览器和Mozilla浏览器中显示正确的结果。


Replace Data In a Text Node
替换文本节点中的数据

The replaceData() method is used to replace data in a text node.
replaceData()方法的作用是:替换一个文本节点中的数据。

The replaceData() method has three parameters:
replaceData()方法包含下面三个参数:

  • offset - Where to begin replacing characters. Offset value starts at zero
    offset - 指定替换字符的起始位置。起始值为0
  • length - How many characters to replace
    length - 指定一共需要替换字符的数量
  • string - The string to insert
    string - 指定需要插入的字符

The following code fragment will replace the eight first characters from the text node in the first <title> element with "Easy":
下面的代码片断将用“Easy”来替换位于第一个<title>元素中文本节点的8个首字符:

xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.replaceData(0,8,"Easy");

DOM 建立 Nodes
w3pop.com / 2006-09-21

p.gifDOM 更换 Nodes DOM 添加 Nodes n.gif

Examples
实例

In the examples below, we will use the XML file books.xml, and the JavaScript function loadXMLDoc().
在下面的例子中,我们会用到这个XML文件:books.xml以及JavaScript 函数loadXMLDoc()。

创建一个元素
This example uses createElement() to create a new element node, and appendChild() to add it to a node list.
此例通过createElement() 方法创建了一个新的元素,并将其放入节点列表。

创建一个新的属性
This example uses createAttribute() to create a new attribute node, and setAttributeNode() to insert it to an element.
此例通过createAttribute() 方法创建了一个新的属性,并把它放入了现有的元素中。

创建了一个新的文本节点
创建了一个新的文本节点
This example uses createTextNode() to create a new text node, and appendChild() to add it to a node list.
此例通过createTextNode() method创建了一个新的文本节点,并把它放入了现有的元素中。

创建了一个新的CDATA片段
This example uses createCDATAsection() to create a CDATA section node, and appendChild() to add it to a node list.
此例通过createCDATAsection() method创建了一个CDATA片断,并把它放入节点列表中。

创建一个注释节点
This example uses createComment() to create a comment node, and appendChild() to add it to a node list.
这个案例使用createComment()创建了一个注释节点,并通过使用appendChild()将它添加到了节点列表中。


Create an Element
创建一个新元素

The createElement() method creates a new element node.
createElement()方法创建了一个全新的元素节点。

The following code fragment creates an element (<edition>), and adds it after the last child of each <book> element:
下面的代码片断创建了一个全新<edition>元素,并把它添加到所有的<book>元素中:

xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName('book');
var newel
for (i=0;i<x.length;i++)
{
newel=xmlDoc.createElement('edition');
x[i].appendChild(newel);
}


Create an Attribute
创建一个新属性

The createAttribute() creates a new attribute node.
createAttribute()创建了一个全新的attribute[属性]节点。

The following code fragment creates an "edition" attribute and adds it to all <book> elements:
下面的代码片断创建了一个新"edition"属性,并把它添加到了<book>所有的属性中:

xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName('book');
var newatt;
for (i=0;i<x.length;i++)
{
newatt=xmlDoc.createAttribute("edition");
newatt.value="first";
x[i].setAttributeNode(newatt);
}


Create a Text Node
创建一个新文本节点

The createTextNode() method creates a new text node.
TextNode()创建了一个全新的文本节点。

The following code fragment creates an element (<edition>), with a text node ('First') in it, and adds it after the last child of each <book> element:
下面的代码片断创建了一份带有文本节点的全新的<edition>元素,并把它添加到所有的<book>元素中:

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);
}
 

Create a CDATA Section Node
创建一个新CDATA片断

The createCDATASection() method creates a new CDATA section node.
createCDATASection()方法创建了一个可以添加到现有节点的新CDATA片断。

The following code fragment creates a CDATA section, and adds it after the last child of each <book> element:
下面的代码片断显示了如何创建CDATA片断以及如何把它添加到每一个<book>元素中 :

xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName('book');
var newCDATA,newtext;
newtext="Special Offer & Book Sale";
for (i=0;i<x.length;i++)
{
newCDATA=xmlDoc.createCDATASection(newtext);
x[i].appendChild(newCDATA);
}


Create a Comment Node
创建一个注释节点

The createComment() method creates a new comment node.
使用createComment()方法创建一个新的注释节点

The following code fragment creates a comment node, and adds it after the last child of each <book> element:
下面的代码片段创建了一个注释节点,并将其添加在每个<book>元素中最后一个子元素的后面:

xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName('book');
var newComment,newtext;
newtext="Revised September 2006";
for (i=0;i<x.length;i++)
{
newComment=xmlDoc.createComment(newtext);
x[i].appendChild(newComment);
}

DOM 添加 Nodes
w3pop.com / 2006-09-21

p.gifDOM 建立 Nodes DOM 克隆 Nodes n.gif

Examples
实例

In the examples below, we will use the XML file books.xml, and the JavaScript function loadXMLDoc().
在下面的实例中,我们会用到这个XML文件:books.xml,和Java脚本函数loadXMLDoc()

Add a node to the end of a node list
在节点列表的末端添加一个节点
This example uses createElement() to create a new element, and appendChild() to add it to a node list.
此实例通过appendChild() 方法在每个<book>元素中添加了一个新子元素。

Add a node before a specific node
在指定的现存节点前添加一个新的子元素
This example uses createElement() to create a new element, and insertBefore() to insert it before a specific node.
此实例通过insertBefore() 方法在指定的现有节点之前添加了一个新子元素。

Set a new attribute and attribute value
设置一个新的属性和属性值
This example uses the setAttribute() method to set a new attribute/attribute value.
此实例通过setAttribute() 方法设置了一个新属性/属性值。

Insert data into a text node
在文本节点中插入一个字符串
This example uses insertData() to insert data into a text node.
此实例通过使用insertData() 的方法在一个现有的文本节点中插入一个字符串。


Add a Node to The End of a Node List
在节点列表的末尾添加一个新元素

The appendChild() method is used to add a node after the last child of a specific node.
appendChild() 方法的作用:在指定节点的子节点列表末尾添加一个新节点

This method is useful when the position of the added node is not important.
如果你想将一个元素添加到节点列表,并且该节点位置并不重要时,那么这个方法是非常有用的。

The following code fragment creates an element (<edition>), and adds it after the last child of each <book> element:
下面的代码片断在每个<book>元素中添加了一个新的子元素(<edition>)。

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);
}
 

Insert a Node Before a Specific Node
在现有节点之前插入一个节点

The insertBefore() method is used to insert a node before a specific node.
insertBefore() 方法在指定的现有节点之前插入了一个节点。

This method is useful when the position of the added node is important.
如果你需要在节点列表中添加一个节点并且节点的位置并不重要时,那么这个方法是非常有用的。

The following code fragment creates a new <book> element and inserts it before the last <book> element:
下面代码片断创建了一个新的<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;
var newNode=xmlDoc.createElement("book");
var newTitle=xmlDoc.createElement("title");
var newText=xmlDoc.createTextNode("A Notebook");
newTitle.appendChild(newText);
newNode.appendChild(newTitle);
x.insertBefore(newNode,get_lastchild(x));

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, the get_lastchild() function checks the node type of the last child node of the parameter.
注意:IE浏览器将跳过在节点中产生的空格文本节点(如:跳过新一行字符);然而Mozilla浏览器却不会。因此,在上述案例中,需要使用get_lastchild()函数检验参数中最后一个子节点的节点类型。

Element nodes has a nodeType of 1, so if not the last child of the node in the parameter is an element node, it moves to the previous node, and checks if this node is an element node. This continues until the last child node (which must be an element node) is found. This way, the result will be correct in both Internet Explorer and Mozilla.
元素节点的节点类型为1,因此,如果参数中的最后一个子节点不是一个元素节点,那么它将继续向上一个节点移动,检查这个节点是不是一个元素节点,直到第一次发现这个元素节点为止。通过使用这个方法,可以同时在IE浏览器和Mozilla浏览器中显示正确的结果。


Set a New Attribute and Attribute Value
设置一个新的属性和属性值

The setAttribute() method can be used to change the value of an existing attribute, or to create a new attribute/attribute value for an element.
setAttribute() 方法的作用是:改变现有属性值,或创建一个新属性/元素的属性值。

The following code fragment adds a new attribute/attribute value to each <book> element:
下面的代码片断在每个<book>元素添加了一个新属性/属性值。

xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName("book");
for(i=0;i<x.length;i++)
{
x.item(i).setAttribute("edition","FIRST");
}

Note: If the "edition" attribute already exists, the setAttribute() method will overwrite the attribute's value.
注意:如果"edition"属性已经存在的话,setAttribute() 方法会覆盖属性值。


Insert Data Into a Text Node
把数据插入到一个文本节点

The insertData() method is used to insert data into a text node.
insertData() method作用:在现有文本节点中添加字符。

The insertData() method has two parameters:
insertData() method含有2个参数。

  • offset - Where to begin inserting characters. Offset value starts at zero
    开始端(offset)-从哪儿开始插入字符。开始端初始值为0
  • string - The string to insert
    字符串(string)- 插入的字符串

The following code fragment will add "Easy" to the text node of the first <title> element of the loaded XML:
下面的代码片断会添加源于已加载的XML文件中第一个<title>元素里的文本节点中的字符串”easy”。

xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.insertData(0,"Easy ");

DOM 克隆 Nodes
w3pop.com / 2006-09-21

p.gifDOM 添加 Nodes DOM Node 类型 n.gif

Examples
案例

In the examples below, we will use the XML file books.xml, and the JavaScript function loadXMLDoc().
在下面的例子中,我们需要用到此XML文件:books.xml和Java脚本函数 loadXMLDoc()

 复制一个节点并将它添加到节点列表中
This example uses cloneNode() to copy a node and append it to a node list.
这个案例使用了cloneNode()复制了一个节点并将它添加到了一个节点列表中。


Copy a Node
复制一个节点

The cloneNode() method creates a copy of a specified node.
cloneNode()方法的作用是创建一个指定节点的复制版本。

The cloneNode() method has a parameter (true or false). This parameter indicates if the cloned node should include all attributes and child nodes of the original node.
cloneNode()方法拥有一个参数(true或false)。这个参数指明了被克隆的节点是否应该包含所有的属性以及原始节点中的子节点。

The following code fragment copies the first <book> node and then adds the copy to the end of the node list:
下面的代码片断复制了第一个<book>节点并将它添加到节点列表的末尾:

xmlDoc=loadXMLDoc("books.xml");
var oldNode=xmlDoc.getElementsByTagName('book')[0];
var newNode=oldNode.cloneNode(true);
xmlDoc.documentElement.appendChild(newNode);

//Output all titles
var y=xmlDoc.getElementsByTagName("title");
for (i=0;i<y.length;i++)
{
document.write(y[i].childNodes[0].nodeValue);
document.write("<br />");
}

Output:
输出结果:

Everyday Italian
Harry Potter
XQuery Kick Start
Learning XML
Everyday Italian

DOM Node 类型
w3pop.com / 2006-09-21

p.gifDOM 克隆 Nodes DOM Node n.gif

The DOM presents a document as a hierarchy of node objects.
DOM是一个表示节点对象的数据层(a hierarchy of node objects)文件。


Examples
案例

In the examples below, we will use the XML file books.xml, and the JavaScript function loadXMLDoc().
在下面的案例中,我们会用到这个XML文件:books.xml和JAVA函数loadXMLDoc()

Display nodeName and nodeType of all elements
显示所有元素中的nodeName(节点名称) and nodeType(节点类型)

Display nodeName and nodeValue of all elements
显示所有元素中的nodeName(节点名称) and nodeValue(节点值)


Node Types
节点类型

The following table lists the different W3C node types, and which node types they may have as children:
下面的表格列出了不同的W3C节点类型,每个节点类型中可能包含子类:

Node type
节点类型
Description
描述
Children
子类
DocumentRepresents the entire document (it is the root-node of the DOM tree)
完整的文件(DOM树的根节点)
Element (max. one), ProcessingInstruction, Comment, DocumentType
DocumentFragmentRepresents a "lightweight" Document object, which can hold a portion of a document
“lightweight”文件对象(保留文件的一部分)
Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
DocumentTypeRepresents a list of the entities that are defined for the document
用于定义文件的实体列表
None
EntityReferenceRepresents an entity reference
一个实体参数
Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
ElementRepresents an element
一个元素
Element, Text, Comment, ProcessingInstruction, CDATASection, EntityReference
AttrRepresents an attribute. Note: Attributes differ from the other node types because they are not considered child nodes of a parent
一个属性
注意:属性与其它节点类型不同,因为它们不是同一父节点的子节点。
Text, EntityReference
ProcessingInstructionRepresents a "processing instruction"
“处理指令(processing instruction)”
None
CommentRepresents a comment
注释
None
TextRepresents textual content (character data) in an element or attribute
处于一个元素或一个属性中的文本内容(字符数据)
None
CDATASectionRepresents a block of text that may contains characters that would otherwise be treated as markup
一块包含字符的文本区,这里的字符也可以是标记(markup)
None
EntityRepresents an entity
实体
Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
NotationRepresents a notation declared in the DTD
在DTD中声明的符号
None


Node Types - Return Values
节点类型-返回值

Below is a list of what the nodeName and the nodeValue properties will return for each nodetype:
下面的列表详细说明了每个节点属性(nodetype)返回的节点名称(nodeName)和节点类型(nodetype):

Node type
节点
nodeName returns
节点名称
nodeValue returns
节点值
Document#document
文档
null
DocumentFragment#document fragment
文档片断
null
DocumentTypedoctype name
文档类型名称
null
EntityReferenceentity reference name
实体参数名称
null
Elementelement name
元素名称
null
Attrattribute name
属性名称
attribute value
ProcessingInstructiontarget
目标
content of node
Comment#comment
注释
comment text
Text#text
文本
content of node
CDATASection#cdata-section
CDATA-部分
content of node
Entityentity name
实体名称
null
Notationnotation name
符号名称
null


NodeTypes - Named Constants
节点类型 – 名称常量

NodeType
节点类型
Named Constant
名称常量
1ELEMENT_NODE
2ATTRIBUTE_NODE
3TEXT_NODE
4CDATA_SECTION_NODE
5ENTITY_REFERENCE_NODE
6ENTITY_NODE
7PROCESSING_INSTRUCTION_NODE
8COMMENT_NODE
9DOCUMENT_NODE
10DOCUMENT_TYPE_NODE
11DOCUMENT_FRAGMENT_NODE
12NOTATION_NODE

DOM Node
w3pop.com / 2006-09-21

p.gifDOM Node 类型 DOM NodeList n.gif

The Node object is the primary data type for the entire DOM.
节点对象是整个DOM中最主要的数据类型。

The Node object represents a single node in the document tree.
节点对象代表了节点树中的一个单独的节点。

A node can be an element node, an attribute node, a text node, or any other of the node types explained in the "Node types" chapter.
这里说的节点可以是:元素节点、属性节点、文本节点以及所有在“Node types[节点类型]”这章中所提到的所有类型的节点。

Notice that while all objects inherits the Node properties / methods for dealing with parents and children, not all objects can have parents or children. For example, Text nodes may not have children, and adding children to such nodes results in a DOM error.
注意:尽管所有的对象都继承了用以处理子类节点或父类节点的节点属性或节点对象,但是并不是所有的对象有包含子类或是父类。举个例子来说,文本节点中可能不包含子类,所以将子类节点添加到文本节点中可能会导致一个DOM错误。

IE: Internet Explorer, F: Firefox[火狐], O: Opera, W3C: World Wide Web Consortium (Internet Standard) | 万维网联盟(国际标准)

Node Object Properties
节点对象属性

属性描述IEFOW3C
baseURIReturns the absolute base URI of a node
返回一个节点的绝对基准URL
No1NoYes
childNodesReturns a NodeList of child nodes for a node
返回一个节点的子节点的节点列表
519Yes
firstChildReturns the first child of a node
返回一个节点的第一个子节点
519Yes
lastChildReturns the last child of a node
返回一个节点的最后一个子节点
519Yes
localNameReturns the local part of the name of a node
返回一个节点的本地名称
No19Yes
namespaceURIReturns the namespace URI of a node
返回一个节点的命名空间的URI
No19Yes
nextSiblingReturns the node immediately following a node
直接返回下一个节点
519Yes
nodeNameReturns the name of a node, depending on its type
返回指定节点类型的节点名称
519Yes
nodeTypeReturns the type of a node
返回节点类型
519Yes
nodeValueSets or returns the value of a node, depending on its type
设置或返回指定节点类型的节点值
519Yes
ownerDocumentReturns the root element (document object) for a node
返回节点的根元素(文档对象)
519Yes
parentNodeReturns the parent node of a node
返回一个节点的父节点
519Yes
prefixSets or returns the namespace prefix of a node
设置或返回一个节点的命名空间前缀
No19Yes
previousSiblingReturns the node immediately before a node
直接返回前面一个节点
519Yes
textContentSets or returns the textual content of a node and its descendants
设置或返回当前节点及其子节点的文本内容
No1NoYes
textReturns the text of a node and its descendants. IE-only property
返回当前节点及其子节点的文本。仅IE支持
5NoNoNo
xmlReturns the XML of a node and its descendants. IE-only property
返回当前节点及其子节点的XML。仅IE支持
5NoNoNo

Node Object Methods
节点对象方法

方法描述IEFOW3C
appendChild()Adds a new child node to the end of the list of children of a node
将一个新的子节点添加到的一个节点中的子类节点列表末尾
519Yes
cloneNode()Clones a node
克隆一个节点
519Yes
compareDocumentPosition()Compares the document position of two nodes
比较两个节点的文档位置
No1NoYes
getFeature(feature,version)Returns a DOM object which implements the specialized APIs of the specified feature and version
返回用于执行包含指定特征和版本的特定APIs的DOM对象
  NoYes
getUserData(key)Returns the object associated to a key on a this node. The object must first have been set to this node by calling setUserData with the same key
返回与当前节点的键相关的对象
  NoYes
hasAttributes()Returns true if a node has any attributes, otherwise it returns false
如过节点包含所有属性,则返回true;反之,则返回false
519Yes
hasChildNodes()Returns true if a node has any child nodes, otherwise it returns false
如果一个节点中包含子节点,则返回true;反之,则返回false
519Yes
insertBefore()Inserts a new child node before an existing child node
在当前子节点之前插入一个新的子节点
519Yes
isDefaultNamespace(URI)Returns whether the specified namespaceURI is the default
返回是否默认当前指定的namespaceURI[命名空间URI]
  NoYes
isEqualNode()Checks if two nodes are equal
检验如果两个节点相等
NoNoNoYes
isSameNode()Checks if two nodes are the same node
检验两个节点是否相同
No1NoYes
isSupported(feature,version)Returns whether a specified feature is supported on a node
返回某个节点是否支持指定的特征
  9Yes
lookupNamespaceURI()Returns the namespace URI matching a specified prefix
返回与一个与指定的前缀相匹配的命名空间的URI
No1NoYes
lookupPrefix()

Returns the prefix matching a specified namespace URI
返回与一个与指定的命名空间的URI相匹配的前缀

No1NoYes
normalize()Puts all text nodes underneath a node (including attributes) into a "normal" form where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes
其作用是规范化节点。它将一个节点(包括属性)下的所有文本节点按照规范化结构分隔文本节点(如:元素、注释、处理结构、CDATA、片断区域以及实体参数)的标准格式进行处理。这样操作后,节点中既不会出现相邻节点也不会出现空节点。
519Yes
removeChild()Removes a child node
删除一个子节点
519Yes
replaceChild()Replaces a child node
替换一个子节点
519Yes
setUserData(key,data,handler)Associates an object to a key on a node
将一个对象赋到一个节点中的一个键中
  NoYes

DOM NodeList
w3pop.com / 2006-09-21

p.gifDOM Node DOM NamedNodeMap n.gif

The nodes in the NodeList can be accessed through their index number (starting from 0).
节点列表中的节点可以同过其对应的索引数字进行访问(从0开始计数)

The NodeList keeps itself up-to-date. If an element is deleted or added, in the node list or the XML document, the list is automatically updated.
节点列表将会自我更新。如果节点列表或XML文档中的元素被添加或是删除,那么列表中的元素将会自动更新。

Note: In a node list, the nodes are returned in the order in which they are specified in the XML.
注意:在一个节点列表中,所有的节点将按照在XML中指定的顺序返回。

IE: Internet Explorer, F: Firefox[火狐], O: Opera, W3C: World Wide Web Consortium (Internet Standard) | 万维网联盟(国际标准)

NodeList Object Properties
节点列表对象道具

Property属性Description描述IEFOW3C
lengthReturns the number of nodes in a node list
返回一个节点列表中的节点数量
519Yes

NodeList Object Methods
节点列表对象方法

Method方法Description描述IEFOW3C
item()Returns the node at the specified index in a node list
返回节点列表中指定的索引节点
519Yes

DOM NamedNodeMap
w3pop.com / 2006-09-21

p.gifDOM NodeList DOM Document n.gif

The nodes in the NamedNodeMap can be accessed through their name.
NamedNodeMap[指定节点映射]中的节点可以通过它们的名称进行访问。

The NamedNodeMap keeps itself up-to-date. If an element is deleted or added, in the node list or the XML document, the list is automatically updated.
NamedNodeMap[指定节点映射]将会自我更新。如果位于节点列表中或XML文档中的一个元素被添加或是删除,那么该列表将会自动更新。

Note: In a named node map, the nodes are not returned in any particular order.
注意:在一个指定的节点映射中,节点不会以任何特定的顺序返回。

IE: Internet Explorer, F: Firefox[火狐], O: Opera, W3C: World Wide Web Consortium (Internet Standard) | 万维网联盟(国际标准)

NamedNodeMap Object Properties
NamedNodeMap[指定节点映射]对象属性

Property
属性
Description
描述
IEFOW3C
lengthReturns the number of nodes in the list
返回列表中的节点数量
519Yes

NamedNodeMap Object Methods
NamedNodeMap[指定节点映射]对象方法

Method
方法
Description
描述
IEFOW3C
getNamedItem()Returns the specified node (by name)
通过本地名称返回指定的节点
519Yes
getNamedItemNS()Returns the specified node (by name and namespace)
通过本地名和命名空间的URI得到指定的节点
  9Yes
item()Returns the node at the specified index
返回指定索引的节点
519Yes
removeNamedItem()Removes the specified node (by name)
通过本地名称删除指定的节点
619Yes
removeNamedItemNS()Removes the specified node (by name and namespace)
通过本地名和命名空间的URI删除指定的节点
  9Yes
setNamedItem()Sets the specified node (by name)
通过本地名称设置指定的节点
  9Yes
setNamedItemNS()Sets the specified node (by name and namespace)
通过本地名和命名空间的URI设置指定的节点
  9Yes

DOM Document
w3pop.com / 2006-09-21

p.gifDOM NamedNodeMap DOM DocumentType n.gif

The Document object represents the entire XML document.
Document[文档]对象代表了整个XML文档。


The Document object
文档对象

The Document object is the root of a document tree, and gives us the primary access to the document's data.
文档对象是文档树的“根元素”,我们主要是通过它来访问文档数据的。

Since element nodes, text nodes, comments, processing instructions, etc. cannot exist outside the document, the Document object also contains methods to create these objects. The Node objects have a ownerDocument property which associates them with the Document where they were created.
因为元素节点、文本节点、注释、处理指令等等都不能存在于文档之外,文档对象有包含了创建这些对象的方法。节点对象拥有一个“ownerDocument”属性,通过这个属性可以将文档与该文档内创建的对象关联起来。

IE: Internet Explorer, F: Firefox[火狐], O: Opera, W3C: World Wide Web Consortium (Internet Standard) | 万维网联盟(国际标准)

Document Object Properties
文档对象属性

Property
属性
Description
描述
IEFOW3C
asyncSpecifies whether downloading of an XML file should be handled asynchronously or not
指定XML文件的下载是否与XML的处理异步进行
51.59No
childNodesReturns a NodeList of child nodes for the document
返回文档中的子节点列表
519Yes
doctypeReturns the Document Type Declaration associated with the document
返回与文档相关联的文档类型声明
619Yes
documentElementReturns the root node of the document
返回文档中的根节点
519Yes
documentURISets or returns the location of the document
设置或返回文档的位置
No19Yes
domConfigReturns the configuration used when normalizeDocument() is invoked
返回当调用normalizeDocument()时使用的配置
  NoYes
firstChildReturns the first child node of the document
返回文档中的第一个子节点
519Yes
implementationReturns the DOMImplementation object that handles this document
返回处理该文档的DOMImplementation对象
No19Yes
inputEncodingReturns the encoding used for the document (when parsing)
返回用于解析文档的编码
No1NoYes
lastChildReturns the last child node of the document
返回文档的最后一个子节点
519Yes
nodeNameReturns the name of a node (depending on its type)
返回节点名称(依据其类型决定)
519Yes
nodeTypeReturns the node type of a node
返回节点类型
519Yes
nodeValueSets or returns the value of a node (depending on its type)
设置或返回节点值(依据其类型决定)
519Yes
strictErrorCheckingSets or returns whether error-checking is enforced or not
设置或返回是否要强制进行错误检查
No1NoYes
textReturns the text of a node and its descendants. IE-only property
返回一个节点及其子节点的文本内容。仅IE支持该属性
5NoNoNo
xmlReturns the XML of a node and its descendants. IE-only property
返回一个节点及其子节点的XML内容。仅IE支持该属性
5NoNoNo
xmlEncodingReturns the XML encoding of the document
返回文档的XML编码
No1NoYes
xmlStandaloneSets or returns whether the document is standalone
设置或返回该文档是否独立的
No1NoYes
xmlVersionSets or returns the XML version of the document
设置或返回文档的XML版本
No1NoYes

Document Object Methods
文档对象方法

Method
方法
Description
描述
IEFOW3C
adoptNode(sourcenode)Adopts a node from another document to this document, and returns the adopted node
将另一文档中的节点应用于当前文档中,并返回这个被应用的节点
  NoYes
createAttribute(name)Creates an attribute node with the specified name, and returns the new Attr object
创建指定与节点名称对应的属性节点,并返回全新的attr[属性]对象
619Yes
createAttributeNS(uri,name)Creates an attribute node with the specified name and namespace, and returns the new Attr object
通过指定的名称或命名空间创建一个属性节点,并返回全新的attr[属性]对象
  9Yes
createCDATASection()Creates a CDATA section node
创建一个CDATA片断节点
519Yes
createComment()Creates a comment node
创建一个注释节点
619Yes
createDocumentFragment()Creates an empty DocumentFragment object, and returns it
创建一个空的DocumentFragment对象并返回它
519Yes
createElement()Creates an element node
创建一个元素节点
519Yes
createElementNS()Creates an element node with a specified namespace
通过指定的命名空间创建一个元素节点
No19Yes
createEntityReference(name)Creates an EntityReference object, and returns it
创建一个EntityReference对象并返回它
5 NoYes
createProcessingInstruction(target,data)Creates a ProcessingInstruction object, and returns it
创建一个ProcessingInstruction对象并返回它
5 9Yes
createTextNode()Creates a text node
创建一个文本节点
519Yes
getElementById(id)Returns the element that has an ID attribute with the given value. If no such element exists, it returns null
返回指定ID对应的元素值。如果该元素不存在,那么返回空值
519Yes
getElementsByTagName()Returns a NodeList of all elements with a specified name
通过指定的名称返回所有元素的节点列表
519Yes
getElementsByTagNameNS()Returns a NodeList of all elements with a specified name and namespace
通过指定的名称和命名空间返回所有元素的节点列表
No19Yes
importNode(nodetoimport,deep)Imports a node from another document to this document. This method creates a new copy of the source node. If the deep parameter is set to true, it imports all children of the specified node. If set to false, it imports only the node itself. This method returns the imported node
将另一文档中的节点导入该文档。这个文档创建了源节点的全新复制版本。如果deep[深度]参数设置为true,那么它将导入指定节点中所有的子节点;如果设置为false,那么它将导入该节点本身。通过这个方法可以返回被导入的节点对象
  9Yes
normalizeDocument()   NoYes
renameNode()Renames an element or attribute node
重命名一个元素或属性节点
  NoYes

DOM DocumentType
w3pop.com / 2006-09-21

p.gifDOM Document DOM ProcessingInstr n.gif

The DocumentType object provides an interface to the entities defined for an XML document.
DocumentType[文档类型]对象提供了一个用于定义XML文档的实体对象。


The DocumentType object
DocumentType[文档类型]对象

Each document has a DOCTYPE attribute that whose value is either null or a DocumentType object.
每个文档都包含一个DOCTYPE属性,该属性值可以是一个空值或是一个DocumentType[文档类型]对象。

The DocumentType object provides an interface to the entities defined for an XML document.
DocumentType[文档类型]对象提供了一个用于定义XML文档的实体对象。

IE: Internet Explorer, F: Firefox[火狐], O: Opera, W3C: World Wide Web Consortium (Internet Standard) | 万维网联盟(国际标准)

DocumentType Object Properties
DocumentType[文档类型]对象属性

Property
属性
Description
描述
IEFOW3C
entitiesReturns a NamedNodeMap containing the entities declared in the DTD
返回一个包含DTD声明实体的NamedNodeMap[指定节点映射]
6No9Yes
internalSubsetReturns the internal DTD as a string
以字符串的形式返回内部DTD
NoNoNoYes
nameReturns the name of the DTD
返回DTD名称
619Yes
notationsReturns a NamedNodeMap containing the notations declared in the DTD
返回一个包含DTD声明符号的NamedNodeMap[指定节点映射]
6No9Yes
systemIdReturns the system identifier of the external DTD
返回用于确认外部DTD的系统
No19Yes

DOM ProcessingInstr
w3pop.com / 2006-09-21

p.gifDOM DocumentType DOM 元素 n.gif

The ProcessingInstruction object represents a processing instruction.
ProcessingInstruction[处理指令]对象表示一个处理指令。


The ProcessingInstruction object
ProcessingInstruction[处理指令]对象

The ProcessingInstruction object represents a processing instruction.
ProcessingInstruction[处理指令]对象表示一个处理指令。

A processing instruction is used as a way to keep processor-specific information in the text of the XML document.
处理指令用于保持XML文档文本中特定处理器信息的方法。

IE: Internet Explorer, F: Firefox[火狐], O: Opera, W3C: World Wide Web Consortium (Internet Standard) | 万维网联盟(国际标准)

ProcessingInstruction Object Properties
ProcessingInstruction[处理指令]对象

Property
属性
Description
描述
IEFOW3C
dataSets or returns the content of this processing instruction
设置或返回处理指令的内容
  NoYes
targetReturns the target of this processing instruction
返回处理指令的目标
  NoYes

DOM 元素
w3pop.com / 2006-09-21

p.gifDOM ProcessingInstr DOM Attribute n.gif

The Element object represents an element in an XML document. Elements may contain attributes, other elements, or text. If an element contains text, the text is represented in a text-node.
元素对象代表了一个XML文档中的元素。元素可以包含属性、其它元素或文本。如果元素包含了文本,那么将在文本节点中描述文本。

IMPORTANT! Text is always stored in text nodes. A common error in DOM processing is to navigate to an element node and expect it to contain the text. However, even the simplest element node has a text node under it. For example, in <year>2005</year>, there is an element node (year), and a text node under it, which contains the text (2005).
重要信息!文本通常是存储在文本节点中的。在DOM处理中经常会发生的一个错误便是对元素节点进行操作并期待该节点能够包含这个文本。然而,即使是最简单的元素节点中,都包含了文本节点。举个例子来说,在<year>2005</year>中,元素节点(year)中包含了文本节点,该文本节点中又包含了文本(2005)。

Because the Element object is also a Node, it inherits the Node object's properties and methods.
因为元素节点也是一个节点,它继承了节点对象的属性和方法。

IE: Internet Explorer, F: Firefox[火狐], O: Opera, W3C: World Wide Web Consortium (Internet Standard) | 万维网联盟(国际标准)

Element Object Properties
元素对象属性

Property
属性
Description
描述
IEFOW3C
attributesReturns a NamedNodeMap of attributes for the element
返回元素属性的NamedNodeMap[指定节点映射]
519Yes
baseURIReturns the absolute base URI of the element
返回元素的绝对基准URI
No1NoYes
childNodesReturns a NodeList of child nodes for the element
返回元素的子节点列表
519Yes
firstChildReturns the first child of the element
返回元素的第一个子节点
519Yes
lastChildReturns the last child of the element
返回元素的最后一个子节点
519Yes
localNameReturns the local part of the name of the element
返回元素的本地名称
No19Yes
namespaceURIReturns the namespace URI of the element
返回元素的命名空间URI
No19Yes
nextSiblingReturns the node immediately following the element
直接返回下一个元素节点
519Yes
nodeNameReturns the name of the node, depending on its type
返回于指定类型相对应的节点名称
519Yes
nodeTypeReturns the type of the node
返回节点类型
519Yes
ownerDocumentReturns the root element (document object) for an element
返回一个元素的根元素(文档对象)
519Yes
parentNodeReturns the parent node of the element
返回元素的父类节点
519Yes
prefixSets or returns the namespace prefix of the element
设置或返回元素的命名空间前缀
No19Yes
previousSiblingReturns the node immediately before the element
直接返回上一个元素节点
519Yes
schemaTypeInfoReturns the type information associated with the element
返回与元素相关的类型信息
  NoYes
tagNameReturns the name of the element
返回元素名称
519Yes
textContentSets or returns the text content of the element and its descendants
设置或返回元素及其子元素的文本内容
No1NoYes
textReturns the text of the node and its descendants. IE-only property
设置或返回元素及其子元素的文本。仅IE支持该属性
5NoNoNo
xmlReturns the XML of the node and its descendants. IE-only property
设置或返回元素及其子元素的XML。仅IE支持该属性
5NoNoNo

Element Object Methods
元素对象方法

Method
方法
Description
描述
IEFOW3C
appendChild()Adds a new child node to the end of the list of children of the node
在指定节点的子节点列表末尾添加一个新的子节点
519Yes
cloneNode()Clones a  node
克隆一个节点
519Yes
compareDocumentPosition()Compares the document position of two nodes
比较两个节点的文档位置
No1NoYes
getAttribute()Returns the value of an attribute
返回一个属性值
519Yes
getAttributeNS()Returns the value of an attribute (with a namespace)
通过指定的命名空间返回节点值
No19Yes
getAttributeNode()Returns an attribute node as an Attribute object
以属性对象的形式返回一个属性节点
519Yes
getAttributeNodeNS()Returns an attribute node (with a namespace) as an Attribute object
通过指定的命名空间并以属性对象的形式返回一个属性节点
No 9Yes
getElementsByTagName()Returns a NodeList of matching element nodes, and their  children
返回一个与指定元素节点及其子节点相匹配的节点列表
519Yes
getElementsByTagNameNS()Returns a NodeList of matching element nodes (with a namespace), and their  children
通过指定的命名空间返回一个与指定元素节点及其子节点相匹配的节点列表
No19Yes
getFeature(feature,version)Returns a DOM object which implements the specialized APIs of the specified feature and version
返回一个用于执行指定特征和版本的APIs的DOM对象
  NoYes
getUserData(key)Returns the object associated to a key on a this node. The object must first have been set to this node by calling setUserData with the same key
返回与当前节点的关键词相关联的对象。该对象首先必须通过请求setUserData 以相同的键值设置为当前节点
  NoYes
hasAttribute()Returns whether an element has any attributes matching a specified name
返回一个元素是否拥有于指定名称相匹配的所有属性
519Yes
hasAttributeNS()Returns whether an element has any attributes matching a specified name and namespace
返回一个元素是否拥有于指定名称与指定命名空间相匹配的所有属性
No19Yes
hasAttributes()Returns whether the element has any attributes
返回元素是否包含属性
519Yes
hasChildNodes()Returns whether the element has any child nodes
返回元素是否包含子节点
519Yes
insertBefore()Inserts a new child node before an existing child node
在现有的子节点之前插入一个全新的子节点
519Yes
isDefaultNamespace(URI)Returns whether the specified namespaceURI is the default
返回当前指定的namespaceURI[命名空间URI]是否是默认的
  NoYes
isEqualNode()Checks if two nodes are equal
检验两个节点是否相等
NoNoNoYes
isSameNode()Checks if two nodes are the same node
检验两个节点是否相同
No1NoYes
isSupported(feature,version)Returns whether a specified feature is supported on the element
返回该指定的特征是否被当前元素支持
  9Yes
lookupNamespaceURI()Returns the namespace URI matching a specified prefix
返回与指定前缀相匹配的命名空间URI
No1NoYes
lookupPrefix()Returns the prefix matching a specified namespace URI
返回与指定命名空间URI相匹配的前缀
No1NoYes
normalize()Puts all text nodes underneath this element (including attributes) into a "normal" form where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes
其作用是规范化节点。它将一个节点(包括属性)下的所有文本节点按照规范化结构分隔文本节点(如:元素、注释、处理结构、CDATA、片断区域以及实体参数)的标准格式进行处理。这样操作后,节点中既不会出现相邻节点也不会出现空节点。
519Yes
removeAttribute()Removes a specified attribute
删除一个指定的属性
519Yes
removeAttributeNS()Removes a specified attribute (with a namespace)
通过一个指定的命名空间删除一个指定的属性
No19Yes
removeAttributeNode()Removes a specified attribute node
删除一个指定的属性节点
519Yes
removeChild()Removes a child node
删除一个子节点
519Yes
replaceChild()Replaces a child node
替代一个子节点
519Yes
setUserData(key,data,handler)Associates an object to a key on the element
将指定的对象与元素的键结合起来
  NoYes
setAttribute()Adds a new attribute
添加一个全新的属性
519Yes
setAttributeNS()Adds a new attribute (with a namespace)
通过一个指定的命名空间添加一个全新的属性
 19Yes
setAttributeNode()Adds a new attribute node
添加一个全新的属性节点
519Yes
setAttributeNodeNS(attrnode)Adds a new attribute node (with a namespace)
通过一个指定的命名空间添加一个全新的属性节点
  9Yes
setIdAttribute(name,isId)If the isId property of the Attribute object is true, this method declares the specified attribute to be a user-determined ID attribute
如果属性对象中的isld属性为true,那么该方法将声明该指定的属性为用户自定义的ID属性
  NoYes
setIdAttributeNS(uri,name,isId)If the isId property of the Attribute object is true, this method declares the specified attribute (with a namespace) to be a user-determined ID attribute
如果属性对象中的isld属性为true,那么该方法将声明该指定的属性(包含命名空间)为用户自定义的ID属性
  NoYes
setIdAttributeNode(idAttr,isId)If the isId property of the Attribute object is true, this method declares the specified attribute to be a user-determined ID attribute
如果属性对象中的isld属性为true,那么该方法将声明该指定的属性为用户自定义的ID属性
  NoYes

DOM Attribute
w3pop.com / 2006-09-21

p.gifDOM 元素 DOM Text n.gif

The Attr object represents an attribute of an Element object. The allowable values for attributes are usually defined in a DTD.
Attr对象代表了元素对象的属性。属性的特许值通常是在DTD中定义。

Because the Attr object is also a Node, it inherits the Node object's properties and methods. However, an attribute does not have a parent node and is not considered to be a child node of an element, and will return null for many of the Node properties.
因为Attr对象也是一个节点,它继承了节点对象的属性和方法。然而,属性并不包含父节点,并且,它也不是一个元素的子节点,它将为多数节点属性返回空值。

IE: Internet Explorer, F: Firefox[火狐], O: Opera, W3C: World Wide Web Consortium (Internet Standard) | 万维网联盟(国际标准)

Attr Object Properties
Attr 对象属性

Property
属性
Description
描述
IEFOW3C
baseURIReturns the absolute base URI of the attribute
返回属性的基准URI
No1NoYes
isIdReturns true if the attribute is known to be of type ID, otherwise it returns false
如果一个属性是已知的ID类型,则返回true(如:包含其主体元素的标志符),否则返回false
NoNoNoYes
localNameReturns the local part of the name of the attribute
返回属性的本地名称
No19Yes
nameReturns the name of the attribute
返回属性名称
519Yes
namespaceURIReturns the namespace URI of the attribute
设置或返回一个属性的命名空间URI
No19Yes
nodeNameReturns the name of the node, depending on its type
返回指定类型所对应的节点名称
519Yes
nodeTypeReturns the type of the node
返回一个节点的类型
519Yes
nodeValueSets or returns the value of the node, depending on its type
设置或返回指定的类型所对应的节点值
519Yes
ownerDocumentReturns the root element (document object) for an attribute
返回一个节点的根元素(文档对象)
519Yes
ownerElementReturns the element node the attribute is attached to
返回指定属性所附属的元素节点
No19Yes
prefixSets or returns the namespace prefix of the attribute
设置或返回一个属性的命名空间前缀
No19Yes
schemaTypeInfoReturns the type information associated with this attribute
返回与属性相关的类型信息
NoNoNoYes
specifiedReturns true if the attribute value is set in the document, and false if it's a default value in a DTD/Schema.
如果属性值已在文档中设置,则返回true;如果属性值是DTD/Schema中的默认值,则返回false
519Yes
textContentSets or returns the textual content of an attribute
设置或返回一个属性的文本内容
No19Yes
textReturns the text of the attribute. IE-only property
返回一个属性的文本。仅IE支持
5NoNoNo
valueSets or returns the value of the attribute
返回一个属性值。
519Yes
xmlReturns the XML of the attribute. IE-only property
返回一个属性的XML。仅IE支持
5NoNoNo

DOM Text
w3pop.com / 2006-09-21

p.gifDOM Attribute DOM CDATA n.gif

The Text object represents the textual content of an element or attribute.
文本对象代表了一个元素或属性的文本内容。

IE: Internet Explorer, F: Firefox[火狐], O: Opera, W3C: World Wide Web Consortium (Internet Standard) | 万维网联盟(国际标准)

Text Object Properties
文本对象属性

Property
属性
Description
描述
IEFOW3C
dataSets or returns the text of the element or attribute
设置或返回一个元素或属性的文本
619Yes
isElementContentWhitespaceReturns true if the text node contains content whitespace, otherwise it returns false
如果文本节点包含内容空行,则返回true;否则返回false
NoNoNoYes
lengthReturns the length of the text of the element or attribute
以字符的形式返回一个节点的文本长度
619Yes
wholeTextReturns all text of text nodes adjacent to this node, concatenated in document order
返回所有与当前节点相邻的文本节点,并按照文档中的顺序连接
NoNoNoYes

Text Object Methods
文本对象方法

Method
方法
Description
描述
IE FOW3C
appendData()Appends data to the node
在一个文本节点的末尾添加一个字符串
619Yes
deleteData()Deletes data from the node
删除一个文本节点中的数据
619Yes
insertData()Inserts data into the node
将数据插入文本节点中
619Yes
replaceData()Replaces data in the node
替换文本节点中的数据
619Yes
replaceWholeText(text)Replaces the text of this node and all adjacent text nodes with the specified text
用指定的文本替换当前节点中的文本以及所有相邻的文本节点
NoNoNoYes
splitText()Splits this node into two nodes at the specified offset, and returns the new node that contains the text after the offset
在指定的起始位置将指定的文本节点拆分成两个节点
619Yes
substringData()Extracts data from the node
将获取文本节点中的数据
619Yes

DOM CDATA
w3pop.com / 2006-09-21

p.gifDOM Text DOM Comment n.gif

The CDATASection object represents a CDATA section in a document.


Examples

In the examples below, we will use the XML file books.xml, and the JavaScript function loadXMLDoc().

createCDATASection() - Create a CDATA section node

The CDATASection object
CDATASection 对象

The CDATASection object represents a CDATA section in a document. 
 CDATASection 对象代表了文档中CDATA片断。

A CDATA section contains text that will NOT be parsed by a parser. Tags inside a CDATA section will NOT be treated as markup and entities will not be expanded. The primary purpose is for including material such as XML fragments, without needing to escape all the delimiters.
CDATA片断包含了不会被解析器解析的文本。CDATA片断中的标签将不会被看成标记语言,并且,实体也不会得到扩展。主要目的是为了在不转义所有的定界符的情况下包含诸如XML片断的材料。

The only delimiter that is recognized in a CDATA section is "]]>" - which indicates the end of the CDATA section. CDATA sections cannot be nested.
CDATA片断能够认出的定界符号是“]]>”,它指明了CDATA片断的结尾。CDATA片断不能被嵌套。

IE: Internet Explorer, F: Firefox[火狐], O: Opera, W3C: World Wide Web Consortium (Internet Standard) | 万维网联盟(国际标准)

CDATASection Object Properties
CDATASection 对象属性

Property
属性
Description
描述
IEFOW3C
dataSets or returns the text of this node
设置或返回已选的节点数据
61NoYes
lengthReturns the length of the CDATA section
返回已选节点中的字符数量
61NoYes

CDATASection Object Methods
CDATASection 对象方法

Method
方法
Description
描述
IE FOW3C
appendData()Appends data to the node
将数据添加到CDATA节点末尾
61NoYes
deleteData()Deletes data from the node
删除CDATA节点中的数据
61NoYes
insertData()Inserts data into the node
将数据插入一个CDATA节点中
61NoYes
replaceData()Replaces data in the node
替换CDATA节点中的数据
61NoYes
splitText()Splits the CDATA node into two nodes
将指定的CDATA节点拆分成两个节点
61No 
substringData()Extracts data from the node
获取CDATA节点中的数据
61NoYes

DOM Comment
w3pop.com / 2006-09-21

p.gifDOM CDATA DOM HttpRequest n.gif

The Comment object represents the content of comment nodes in a document.
Comment对象代表了文档中注释节点的内容。


Examples
案例

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

createComment() - Create a comment node
createComment() - 创建一个注释节点


The Comment object
注释对象

The Comment object represents the content of comment nodes in a document.
Comment对象代表了文档中注释节点的内容。

IE: Internet Explorer, F: Firefox[火狐], O: Opera, W3C: World Wide Web Consortium (Internet Standard) | 万维网联盟(国际标准)

Comment Object Properties
注释对象属性

Property
属性
Description
描述
IEFOW3C
dataSets or returns the text of this node
设置或返回一个注释文本
619Yes
lengthReturns the length of the text of this node
以字符的形式返回一个注释节点的文本长度
619Yes

Comment Object Methods
注释对象方法

Method
方法
Description
描述
IE FOW3C
appendData()Appends data to the node
在一个注释节点的末尾添加数据
619Yes
deleteData()Deletes data from the node
删除一个注释节点中的数据
619Yes
insertData()Inserts data into the node
将数据插入注释节点中
619Yes
replaceData()Replaces data in the node
替换注释节点中的数据
619Yes
substringData()Extracts data from the node
获取文本节点中的数据
619Yes

DOM HttpRequest
w3pop.com / 2006-09-21

p.gifDOM Comment DOM ParseError n.gif

The XMLHttpRequest object is supported in Internet Explorer 5.0+, Safari 1.2, Mozilla 1.0 / Firefox, Opera 9, and Netscape 7.
Internet Explorer 5.0+, Safari 1.2, Mozilla 1.0 / Firefox, Opera 9, 和 Netscape 7.都支持XMLHttpRequest对象。


What is an HTTP Request?
什么是HTTP Request

With an HTTP request, a web page can make a request to, and get a response from a web server - without reloading the page. The user will stay on the same page, and he or she will not notice that scripts might request pages, or send data to a server in the background.
通过一个HTTP请求,网页可以发送一个请求并从网络服务器端获取一个响应(不需要重新加载页面)。用户会停留在相同的页面上,不会注意到脚本请求页面或从后台把数据传回服务器的过程。

By using the XMLHttpRequest object, a web developer can change a page with data from the server after the page has loaded.
通过使用XMLHttpRequest对象,网络开发者可以在页面加载之后,改变从服务器传回的数据。

Google Suggest is using the XMLHttpRequest object to create a very dynamic web interface: When you start typing in Google's search box, a JavaScript sends the letters off to a server and the server returns a list of suggestions.
Google Suggest(Google 建议)通过XMLHttpRequest来创建一个动态网络界面:当你在Google搜索栏开始键入时,JavaScript程序会向服务器发送信息,服务器也会返回建议列表。


Is the XMLHttpRequest Object a W3C Standard?
XMLHttpRequest对象是W3C标准吗?

The XMLHttpRequest object is not a W3C standard.
XMLHttpRequest对象不是W3C标准。

The W3C DOM Level 3 "Load and Save" specification contains some similar functionality, but these are not implemented in any browsers yet. So, at the moment, if you need to send an HTTP request from a browser, you will have to use the XMLHttpRequest object.
W3C DOM标准3 "Load and Save"(加载和保存)的详细说明中包含了一些类似的功能,但它们还不能在浏览器中执行。所以现在,如果你想从浏览器中发送一个HTTP请求,就需要使用XMLHttpRequest对象。


Creating an XMLHttpRequest Object
创建XMLHttpRequest对象

For Mozilla, Firefox, Safari, Opera, and Netscape:
对于Mozilla, Firefox, Safari, Opera, 和 Netscape而言:

var xmlhttp=new XMLHttpRequest()

For Internet Explorer:
对于IE而言:

var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")

Example
实例

<script type="text/javascript">

var xmlhttp
function loadXMLDoc(url)
{
xmlhttp=null
// code for Mozilla, etc.
if (window.XMLHttpRequest)
  {
  xmlhttp=new XMLHttpRequest()
  }
// code for IE
else if (window.ActiveXObject)
  {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
  }
if (xmlhttp!=null)
  {
  xmlhttp.onreadystatechange=state_Change
  xmlhttp.open("GET",url,true)
  xmlhttp.send(null)
  }
else
  {
  alert("Your browser does not support XMLHTTP.")
  }
}
function state_Change()
{
// if xmlhttp shows "loaded"
if (xmlhttp.readyState==4)
  {
  // if "OK"

  if (xmlhttp.status==200)
    {
    // ...some code here...
    }
  else
    {
    alert("Problem retrieving XML data")
    }
  }
}
</script>

Try it yourself using JavaScript
使用JavaScript自己试试看吧!

Note: An important property in the example above is the onreadystatechange property. This property is an event handler which is triggered each time the state of the request changes. The states run from 0 (uninitialized) to 4 (complete). By having the function xmlhttpChange() check for the state changing, we can tell when the process is complete and continue only if it has been successful.
注意:上述实例中,其中一个极其重要的属性就是onreadystatechange属性。这个属性类似一个事件处理器,它是用来激发每次发出的请求改变的。它的情况从0 (未开始)运行到4(完成)。我们通过xmlhttpChange()函数来检查状态的改变来区分什么时候这个过程已经运行完毕,什么时候它还在继续地运行。


Why are we Using async in our Examples?
我们为何在案例中使用同步?

Most of the examples here use the async mode (the third parameter of open() set to true).
这儿大部分例子都用到了同步模式(当第三个参数open()设置为true)

The async parameter specifies whether the request should be handled asynchronously or not. True means that script continues to run after the send() method, without waiting for a response from the server. false means that the script waits for a response before continuing script processing. By setting this parameter to false, you run the risk of having your script hang if there is a network or server problem, or if the request is long (the UI locks while the request is being made) a user may even see the "Not Responding" message. It is safer to send asynchronously and design your code around the onreadystatechange event!
async参数详细指明了请求是否应该被同步处理。True表示在send()运行之后,不等待服务器的响应。False表示在脚本程序继续处理之前,等待服务器的响应。如果你把参数设置成false,在网络服务器出现问题或请求时间过长(UI已被锁住,且正处于请求过程当中)时,用户甚至会收到“无响应(Not Responding)”。这对于异步传输以及onreadystatechange事件的编码设计来说都是非常安全的!


More Examples
更多案例

Load a textfile into a div element with XML HTTP (JavaScript)
通过HTTP(JavaScript)将一个文本文件加载到DIA元素

Make a HEAD request with XML HTTP (JavaScript)
通过XML HTTP(JavaScript)提出一个HEAD请求

Make a specified HEAD request with XML HTTP (JavaScript)
通过XML HTTP(JavaScript)提出一个HEAD请求

List data from an XML file with XML HTTP (JavaScript)
通过XML HTTP(JavaScript)列出XML文件中的数据


XML / ASP

You can also open and send an XML document to an ASP page on the server, analyze the request, and send back the result.
你也可以打开XML文件并将它发送到服务器上的ASP页面,分析请求并传回结果。

<html>
<body>
<script type="text/javascript">
var xmlHttp=new ActiveXObject("Microsoft.XMLHTTP")
xmlHttp.open("GET", "note.xml", false)
xmlHttp.send()
xmlDoc=xmlHttp.responseText
xmlHttp.open("POST", "demo_dom_http.asp", false)
xmlHttp.send(xmlDoc)
document.write(xmlHttp.responseText)

</script>
</body>
</html>

The ASP page, written in VBScript:
用VB脚本语言编写的ASP页面:

<%
set xmldoc = Server.CreateObject("Microsoft.XMLDOM")
xmldoc.async=false
xmldoc.load(request)

for each x in xmldoc.documentElement.childNodes
   if x.NodeName = "to" then name=x.text
next
response.write(name)
%>

You send the result back to the client using the response.write property.
使用response.write属性把结果传回客户端:

For Internet Explorer 5.0+: Try it yourself
IE5.0:你可以自己试一试^_^


The XMLHttpRequest Object Reference
XMLHttpRequest对象参数

Methods方法

Method
方法
Description
描述
abort()Cancels the current request
取消当前请求
getAllResponseHeaders()Returns the complete set of http headers as a string
以字符串的形式返回完整的http headers
getResponseHeader("headername")Returns the value of the specified http header
返回详细的http headers值
open("method","URL",async,"uname","pswd")Specifies the method, URL, and other optional attributes of a request
 指定方式(method)、URI以及其它可选择的请求属性

The method parameter can have a value of "GET", "POST", or "PUT" (use "GET" when requesting data and use "POST" when sending data (especially if the length of the data is greater than 512 bytes.
方式参数可以含有"GET", "POST", 或 "PUT" 值|请求数据用 "GET" ,发送数据(特别是数据长度大于等于512字节的情况下)用“POST”。

The URL parameter may be either a relative or complete URL.
URL参数就是与其相关的相对连接或绝对连接

The async parameter specifies whether the request should be handled asynchronously or not. true means that script processing carries on after the send() method, without waiting for a response. false means that the script waits for a response before continuing script processing
异步(ASync)参数指定了是否需要异步处理请求。True表示在send()运行之后,不等待服务器回应,持续进行脚本处理;False的意思是:在脚本继续处理之前,等待服务器回应。

send(content)Sends the request
发送请求
setRequestHeader("label","value")Adds a label/value pair to the http header to be sent
将一个标签/值(label/value)添加到被发送的http header中

Properties属性

Property
属性
Description
描述
onreadystatechangeAn event handler for an event that fires at every state change
用于处理事件状态变化的事件处理器
readyStateReturns the state of the object:
 返回对象状态:

0 = uninitialized(未初始化)
1 = loading(正在加载)
2 = loaded(已加载)
3 = interactive(交互)
4 = complete (完成)

responseTextReturns the response as a string
以字符串形式返回响应
responseXMLReturns the response as XML. This property returns an XML document object, which can be examined and parsed using W3C DOM node tree methods and properties
以XML形式响应。这个属性返回一个XML文件对象(它可以通过W3C DOM节点树德方法和属性进行检查和解析)
statusReturns the status as a number (e.g. 404 for "Not Found" or 200 for "OK")
以数字的形式返回一个状态(比如:"Not Found"(无法找到)就用404;“ok”就用200来表示)
statusTextReturns the status as a string (e.g. "Not Found" or "OK")
以字符串形式返回状态(如:"Not Found" 、 "OK")

DOM ParseError
w3pop.com / 2006-09-21

p.gifDOM HttpRequest DOM 摘要 n.gif

Microsoft's parseError object can be used to retrieve error information from the Microsoft XML parser.
微软的错误解析(parserError)对象的作用是:从微软的XML解析器中获取错误信息


The parseError Object
错误解析对象(parserError)

When trying to open an XML document, a parser-error may occur.
当需要打开XML文件时,有时可能会出现解析错误(parser-error)。

With the parseError object, you can retrieve the error code, the error text, the line that caused the error, and more.
通过错误解析(parseError)对象,你可以找回错误代码,错误文本,错误生成行以及更多的东西。

Note: The parseError object is not a part of the W3C DOM standard!
注意:错误分析对象不是W3C DOM标准的一部分!


File Error
文件错误

In the following code we will try to load a non-existing file, and display some of its error properties:
在下面代码中我们加载一个不存在的文件,并显示它的部分错误属性:

var xmlDoc = new ActiveXObject("Microsoft.XMLDOM")
xmlDoc.async="false"
xmlDoc.load("ksdjf.xml")

document.write("Error code: " + xmlDoc.parseError.errorCode)
document.write("<br />Error reason: " + xmlDoc.parseError.reason)
document.write("<br />Error line: " + xmlDoc.parseError.line)

Try it yourself
自己尝试一下^_^


XML Error
XML错误

In the following code we let the parser load an XML document that is not well-formed.
在下面代码中,我们让解析器加载了一个不规范的(not well-formed)XML文件。

(You can read more about well-formed and valid XML in our XML tutorial)
(如想了解更多规范有效的XML文件,请访问我们的XML 教程。)

var xmlDoc = new ActiveXObject("Microsoft.XMLDOM")
xmlDoc.async="false"
xmlDoc.load("note_error.xml")

document.write("Error code: " + xmlDoc.parseError.errorCode)
document.write("<br />Error reason: " + xmlDoc.parseError.reason)
document.write("<br />Error line: " + xmlDoc.parseError.line)

Try it yourself or just look at the XML file
自己试试看或者看一下XML文件


The parseError Object's Properties
错误解析(parseError)对象的属性

Property
属性
Description
描述
errorCodeReturns a long integer error code
返回一个长整数(long integer)形错误代码
reasonReturns a string containing the reason for the error
返回包含错误原因的字符串
lineReturns a long integer representing the line number for the error
返回一个指明错误行数的长整数(long integer)
lineposReturns a long integer representing the line position for the error
返回一个指明错误位于哪个行位置的一个长整数(long integer)
srcTextReturns a string containing the line that caused the error
返回错误所在行的一个字符串
urlReturns the URL pointing the loaded document
返回指向已加载文件的URI
fileposReturns a long integer file position of the error
返回指明错误所在文件中的位置的一个长整数(long integer)

DOM 摘要
w3pop.com / 2006-09-21

p.gifDOM ParseError DOM 实例 n.gif

XML DOM Summary
XMLDOM综述

This tutorial has taught you how to access and manipulate XML documents.
这份教程已经教会你如何访问和操作XML文件了。

You have learned that the XML DOM views XML documents as a tree structure of elements embedded within other elements. and that all elements can be accessed through the DOM tree. Their contents can be modified or deleted, and new elements can be created by the DOM.
你已经明白了这点:XML文件将XML文档看作是嵌在其他元素内部的一种树结构,所有的元素都可以通过这个DOM树进行访问。它们的内容可以被修改或删除,甚至可以通过DOM建立新的元素。

You have learned about XML parsers, and how to load XML documents into the parser.
你已经知道了XML解析器是个什么东西以及如何将XML文件加载到解析器中。

You have also been introduced to the most important DOM objects, and how to use them.
你也已经知道了最关键的DOM对象以及使用它们的方法

For more information on XML DOM, please look at our XML DOM examples.
如果想了解更多XML DOM信息,请访问XML DOM 案例.。


Now You Know XML DOM, What's Next?
你已经学习了XML DOM,那接下来要学些什么呢?

The next step is to learn about XSLT.
下一步,我们该了解XSLT了

If you need to validate XML documents, the next step is to learn about DTD and XML Schema.
如果你想检验XML文件有效性,那下一步该了解DTD和XML Schema了。

XSLT

XSLT is the style sheet language for XML files.
XSLT是XML文件的样式表语言。

With XSLT you can transform XML documents into other formats, like XHTML.
通过XSLT你可以把XML文件转换成其它类型,比如:XHTML。

If you want to learn more about XSLT, please visit our XSLT tutorial.
如想了解更多的XSLT的知识,请访问我们的XSLT 教程 。

DTD

The purpose of a DTD is to define which elements and attributes that are legal in an XML document.
DTD的目的是定义XML文件中合法的元素与属性。

A DTD is used to validate XML data.
DTD是用于检验XML数据的正确性和有效性的。

If you want to learn more about DTD, please visit our DTD tutorial.
如果你想要了解更多关于DTD的知识,请访问我们的DTD 教程。

XML Schema will replace DTD.
XMLSchema替换DTD

XML Schema is an XML-based alternative to DTD.
XML Schema是基于XML的,它是DTD的一个替代品。

Unlike DTD, XML Schemas has support for data types and namespaces.
不像DTD,XML Schemas支持数据类型(data types)和命名空间(namespaces)。

If you want to learn more about XML Schema, please visit our XML Schema tutorial.
如想了解更多关于XML Schema的知识,请访问我们的XML Schema 教程。

DOM 实例
w3pop.com / 2006-09-21

p.gifDOM 摘要 DOM 校验器 n.gif

XML DOM Parsing
XML DOM 解析

The XML file used in the examples below: note.xml
我们将在案例中使用下面这个XML文件:note.xml

Parse an XML file - Crossbrowser example
解析一个XML文件 - 交叉浏览器案例

Parse an XML string - Crossbrowser example
解析一个XML字符串 - 交叉浏览器案例

Examples explained
案例解释


XML DOM Traversing Nodes
XML DOM 穿越节点

The XML file used in the examples below: note.xml
我们将在案例中使用下面这个XML文件:note.xml

Traverse a node tree
穿越一个节点树

Examples explained
案例解释


XML DOM Get Nodes
XML DOM 获取节点

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

Use getElementsbyTagname()
使用getElementsbyTagname()

Use getAttribute()
使用getAttribute()

Use getNamedItem()
使用getNameItem()

Examples explained
案例解释


XML DOM Set Nodes
XML DOM设置节点

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

Set a new attribute and attribute value
设置一个全新的属性和属性值

Create a new attribute node
创建一个全新的属性节点

Change an attribute's value
改变一个属性值

Change an item's value
改变一个项的值

Examples explained
案例解释


XML DOM Remove Nodes
XML DOM 删除节点

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

Remove an element
删除一个元素

Remove text from a text node
删除一个文本节点中的文本

Remove an attribute
删除一个属性

Use removeAttributeNode()
使用removeAttributeNode()

Examples explained
案例解释


XML DOM Replace Nodes
XML DOM 替代节点

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

Replace a node in a nodelist
替代节点列表中的一个节点

Replace data in a text node
替代文本节点中的数据

Examples explained
案例解释


XML DOM Create Nodes
XML DOM 创建节点

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

Create an element node
创建一个元素节点

Create an attribute node
创建一个属性节点

Create a text node
创建一个文本节点

Create a CDATA section node
创建一个CDATA片断节点

Create a comment node
创建一个注释节点

Examples explained
案例解释


XML DOM Add Nodes
XML DOM 添加节点

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

Add a node to the end of a node list
将一个节点添加到节点列表的末尾

Add a node before a specific node
将一个节点添加到指定节点的前面

Set a new attribute and attribute value
设置一个全新的属性和属性值

Insert data into a text node
将数据插入一个文本节点中

Examples explained
案例解释


XML DOM Clone Nodes
XML DOM 克隆节点

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

Copy a node and add it to the node list
复制一个节点并把它添加到节点列表中

Examples explained
案例解释

DOM 校验器
w3pop.com / 2006-09-21

p.gifDOM 实例 n.gif

Validate your XML
检验你XML文件的有效性

To help you validate (syntax-check) your xml, we have used Microsoft's XML parser to create an XML validator.
为帮助你检验XML文件的有效性,我们通过微软的XML解析器创建了一个XML有限性检验器。

Paste your XML in the text area below, and validate it by pressing the "Validate" button.
把你的XML文件粘贴到下面的文本区域内,点击Validate按钮进行有效性检验。

<?xml version="1.0" ?> <note> <to>Tove</to> <from>Jani</Ffrom> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>

Validate your XML File
检验你的XML文件的有效性

You can also validate your XML files by typing the URL of your file into the input field below, and then press the "Validate" button
the input field below, and then press the "Validate" button
你也可以在下面的输入栏里输入你文件所在的URI并点击Validate按钮来检验XML文件的有效性。

Filename:
文件名:

If you want to validate an error-free XML file, you can paste the following address into the filename field: http://www.w3schools.com/dom/cd_catalog.xml
如果想检验XML文件是否正确,你可以把下面地址粘贴到文件名栏中:http://www.w3schools.com/dom/cd_catalog.xml

Note: If you get the error "Access denied" when accessing this file, it is because your Internet Explorer security settings do not allow access across domains!
注意:当你访问这份文件时,如果你收到一个“拒绝访问(Access denied)”的错误信息的话,那就说明你的IE安全性设置拒绝访问此域名!

转载于:https://www.cnblogs.com/caoxch/archive/2006/11/18/564370.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值