xml.dom.minidom -> nextElement ?

Alan Kennedy alanmk at hotmail.com
Fri Dec 5 05:49:43 EST 2003


[Alexandre]
> Could someone explain to me why there is no nextElement in minidom ?
> 
> if i execute this :
> ***************************************
> import xml.dom.minidom
> doc = """\
> <root>
>     <item>content1</item>
>     <item>content2</item>
> </root>"""
> dom = xml.dom.minidom.parseString(doc)
> firstItem = dom.getElementsByTagName("item")[0]
> nextItem = firstItem.nextSibling
> print nextItem
> ***************************************
> the result is :
> <DOM Text node "
>     ">

You're possibly being confused by the fact that the <root> element has
*5* children, not 2. There are the 2 obvious children, <item>s 1 and
2. However, the whitespace 

 o between <root> and <item> 
 o between </item> and <item>
 o between </item> and </root>

also create text nodes, which only contain whitespace.

Note also that the nextSibling of the first <item> is *not* the second
<item>, it is the whitespace text node in between them. Which explains
the result printed by your code.

> so if i want the next element i could use "firstItem.nextSibling.nextSibling"
> 
> or write my own nextElement :
> ***************************************
> def nextElement(current):
>     pointer = current.nextSibling
>     if pointer.nodeType == pointer.ELEMENT_NODE:
>         return pointer
>     elif pointer == None:
>         return None
>     else: return getNextElement(pointer)
> ***************************************

Well, you could

1. Navigate over your tree deleting whitespace nodes, before doing
your processing.
2. Write your own nav function which skips whitespace text nodes (as
you have done above).
3. Use Xpath to find nodes in trees.

> But i'm wondering if i am not missing something obvious ?
> Thx in advance for your help.

HTH,

-- 
alan kennedy
------------------------------------------------------
check http headers here: http://xhaus.com/headers
email alan:              http://xhaus.com/contact/alan




More information about the Python-list mailing list