Python-Ref > XML > DOM > Finding your way in a DOM tree
 
 

<-^^->
Moduly
Knihovní funkce

Finding your way in a DOM tree

How to do basic navigation without much pain.
When you need to find your way in a DOM tree, using getElementsByTagName() is the most convenient way in many cases. The following example shows how to emulate a simple XPath-like search using this approach.
Expand/Shrink
<examples>
  <example num="1">
    <title>Example 1</title>
    <text>This is example nr. 1. It shows how an example looks.</text>
  </example>

  <example num="2">
    <title>Example 2</title>
    <text>Another example. Imagine some ingenious text here...</text>
  </example>
</examples>
Zdroj: (dom6-1.py)
  1   import xml.dom.minidom as dom
  2   
  3   doc = dom.parse( "example.xml")
  4   
  5   # we would like to find something similar to XPath "//example//title"
  6   for example_element in doc.getElementsByTagName( "example"):
  7       for title_element in example_element.getElementsByTagName( "title"):
  8           print title_element
stdout:
<DOM Element: title at 0x2b94994a9a28>
<DOM Element: title at 0x2b94994a97e8>
Doba běhu: 49.7 ms
This approach has the disadvantage that you always search using "//", that is, you find any elements with matching name, regardless of the depth they are in. In some cases this might be a problem.
To use a more specific approach to solve the above problem, childNodes might be used.
Expand/Shrink
<examples>
  <example num="1">
    <title>Example 1</title>
    <text>This is example nr. 1. It shows how an example looks.</text>
  </example>

  <example num="2">
    <title>Example 2</title>
    <text>Another example. Imagine some ingenious text here...</text>
  </example>
</examples>
Zdroj: (dom6-2.py)
  1   import xml.dom.minidom as dom
  2   
  3   doc = dom.parse( "example.xml")
  4   
  5   # we would like to find something similar to XPath "//example/title"
  6   for example_element in doc.getElementsByTagName( "example"):
  7       for child in example_element.childNodes:
  8           if isinstance( child, dom.Element) and child.nodeName == "title":
  9               print child
stdout:
<DOM Element: title at 0x2b5a125f0a28>
<DOM Element: title at 0x2b5a125f07e8>
Doba běhu: 49.2 ms