XML DOM定位节点
- Previous page DOM browser
- Next page DOM get node
Nodes can be located by using the relationship between nodes.
Example
The following example uses an XML file books.xml.
Function loadXMLDoc(), located in external JavaScript, used to load XML files.
- Get the parent node of the node
- 本例使用 parentNode 属性来获取节点的父节点。
- 获取节点的首个子节点
- 本例使用 firstChild() 方法和一个自定义函数来获取一个节点的首个子节点。
定位 DOM 节点
通过节点间的关系访问节点树中的节点,通常称为定位节点 ("navigating nodes")。
在 XML DOM 中,节点的关系被定义为节点的属性:
- parentNode
- childNodes
- firstChild
- lastChild
- nextSibling
- previousSibling
下面的图像展示了 books.xml 中节点树的一个部分,并说明了节点之间的关系:

DOM - 父节点
所有的节点都仅有一个父节点。下面的代码定位到 <book> 的父节点:
xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName("book")[0]; document.write(x.parentNode.nodeName);
Example explanation:
- By using loadXMLDoc() Put "books.xml" 载入到 xmlDoc 中
- 获取第一个 <book> 元素
- 输出 "x" 的父节点的节点名
避免空的文本节点
Firefox,以及其他一些浏览器,把空的空白或换行当作文本节点,而 IE 不会这么做。
这会在使用下列属性使产生一个问题:firstChild、lastChild、nextSibling、previousSibling。
为了避免定位到空的文本节点(元素节点之间的空格和换行符号),我们使用一个函数来检查节点的类型:
function get_nextSibling(n) { y=n.nextSibling; while (y.nodeType!=1) { y=y.nextSibling; } return y; }
有了上面的函数,我们就可以使用 get_nextSibling(node) 来代替 node.nextSibling 属性。
代码解释:
元素节点的类型是 1。如果同级节点不是元素节点,就移动到下一个节点,直到找到元素节点为止。通过这个办法,在 IE 和 Firefox 中,都可以得到相同的结果。
获取第一个元素
下面的代码显示第一个 <book> 的第一个元素节点:
<html> <head> <script type="text/javascript" src="loadxmldoc.js"> </script> <script type="text/javascript"> //检查第一个节点是否为元素节点 function get_firstChild(n) { y=n.firstChild; while (y.nodeType!=1) { y=y.nextSibling; } return y; } </script> </head> <body> <script type="text/javascript"> xmlDoc=loadXMLDoc("books.xml"); x=get_firstChild(xmlDoc.getElementsByTagName("book")[0]); document.write(x.nodeName); </script> </body> </html>
Output:
title
Example explanation:
- By using loadXMLDoc() Put "books.xml" Load in xmlDoc
- Use the get_firstChild function on the first <book> to get the first child node within the element node
- Output the node name of the first child node (belonging to an element node)
Example
The following example uses similar functions:
- Previous page DOM browser
- Next page DOM get node