To convert XML in the form of a string into an Element structure, use Section 6.4, “The fromstring() function: Create an element from
a string”. However, there is a
similar function named etree.XMLID() that
does this and also provides a dictionary that allows you
to find elements in a tree by their unique id attribute values.
The XML standard stipulates that any element in any
document can have an id attribute, but
each value of this attribute must be unique within the
document. The intent of this feature is that
applications can refer to any element using its id value.
Here is the general form for this function:
etree.XMLID ( text )
The return value is a tuple (, where:
E, D)
is the
converted XML as an EElement instance
rooting the converted tree, just as if you had called
etree.fromstring(text).
is a
dictionary whose keys are the values of Did attributes in the converted tree, and
each corresponding value is the Element instance that carried that id value.
Here's an example:
>>> SOURCE = '''<dog id="Fido"> ... Woof! ... <cat id="Fluff"> ... Mao? ... </cat> ... <rhino id="ZR"/> ...</dog>''' >>> tree, idMap = etree.XMLID(SOURCE) >>> idList = idMap.keys() >>> idList.sort() >>> for id in idList: ... elt = idMap[id] ... if elt.text is None: ... display = "None" ... else: ... display = elt.text.strip() ... print "Tag %s, text is '%s'" % (elt.tag, display) Tag dog, text is 'Woof!' Tag cat, text is 'Mao?' Tag rhino, text is 'None' >>>