当前位置: 首页 > 网络学院 > XML相关教程 > XML DOM > DOM 获取节点

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 中的 DOM 获取节点


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

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() 方法将返回一份包含所有指定标签名称元素的节点列表,所有元素的排列顺序与它们在源文件中的排列顺序一样。

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
获取一个项的值

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

评论 (0) All

登陆 | 还没注册?