Determining a Nodes Type
You can use the constants built in to the DOM to see what type of node you are dealing with. It may be an element, an attribute, a CDATA section, or a host of other things. (All the node type constants are listed in Appendix D.)
To test a node's type, compare its nodeType attribute to the particular constant you're looking for. For example, a CDATASection instance has a nodeType equal to cdata_section_node. An Element (with potential children) has a nodeType equal to element_node. When traversing a DOM tree, you can test a node at any point to determine whether it is what you're looking for:
for node in nodes.childNodes:
if node.nodeType == node.ELEMENT_NODE:
print "Found it!"
The Node interface has other identifying properties, such as its value and name. The nodeName value represents the tag name for elements, while in a text node the nodeName is simply #text. The nodeValue attribute may be null for elements, and should be the actual character data of a text element or other leaf-type element.
Post a comment