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

6.10. The XMLID() function: Convert text to XML with a dictionary of id values

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 (E, D), where:

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'
>>>