Next / Previous / Contents / TCC Help System / NM Tech homepage

9.5. Element.find(): Find a matching sub-element

You can search for sub-elements of an Element instance E using this method call:

E.find(path[, namespaces=D])

This method searches the Element and its descendants for a single element that fits the pattern described by the path argument.

The path argument is a string describing the element for which you are searching. Possible values include:

"tag"

Find the first child element whose name is "tag".

"tag1/tag2/.../tagn"

Find the first child element whose name is tag1; then, under that child element, find its first child named tag2; and so forth.

For example, if node is an Element instance that has an element child with a tag "county", and that child in turn has an element child with tag "seat", this expression will return the Element corresponding to the "seat" element:

node.find("county/seat")

The optional namespaces argument is a namespace map; see Section 4.3, “Namespace maps”. If supplied, this map is used to interpret namespace prefixes in the path argument.

For example, suppose you have an element someNode, and you want to find a child element named roundtable in the namespace named http://example.com/mphg/, and under that you want to find a child element named knight in the namespace named http://example.org/sirs/ns/. This call would do it:

    nsd = {'mp': 'http://example.com/mphg/',
           'k':  'http://example.org/sirs/ns/'}
    someNode.find('mp:roundtable/k:knight', namespaces=nsd}

Note that the namespace prefixes you define in this way do not need to have any particular value, or to match the namespace prefixs that might be used for these NSURIs in some document's external form.

Warning

The namespaces keyword argument to the .find() method is available only for version 2.3.0 or later of etree.