Next / Previous / Contents / Shipman's homepage

3. Some XML helper routines

Here are some routines to perform common XML extraction tasks.

3.1. getFirstChild(): Get the first child of a given name

Because we validate the input file against the schema, we can get away without a lot of error checking. This routine is used to retrieve a child node of a given element name. It will fail if there is no child node by that name.

txny.py
# - - -   g e t F i r s t C h i l d

def getFirstChild ( node, childName ):
    """Get the first child of a given name.

      [ (node is an et.Element) and
        (childName is a string) ->
          if  node has any child elements named (childName) ->
            return the first such child element
          else -> raise IndexError ]
    """
    return  node.xpath ( childName ) [0]