ElementTree Issue - Search and remove elements

Alain Ketterlin alain at dpt-info.u-strasbg.fr
Wed Oct 17 02:25:52 EDT 2012


Tharanga Abeyseela <tharanga.abeyseela at gmail.com> writes:

> I need to remove the parent node, if a particular match found.

It looks like you can't get the parent of an Element with elementtree (I
would love to be proven wrong on this).

The solution is to find all nodes that have a Rating (grand-) child, and
then test explicitly for the value you're looking for.

> <?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
> <Feed xmlns="http://schemas.xxxx.xx/xx/2011/06/13/xx">
>     <TVEpisode>
[...]
>         <ParentalControl>
>             <System>xxxx</System>
>             <Rating>M</Rating>


> for child in root.findall(".//{http://schemas.CCC.com/CCC/2011/06/13/CC}Rating"):
>        x = child.find('Rating').text
>         if child[1].text == 'NC':
>                 print "found"
>                root.remove('TVEpisode') ?????

Your code doesn't work because findall() already returns Rating
elements, and these have no Rating child (so your first call to find()
fails, i.e., returns None). And list indexes starts at 0, btw.

Also, Rating is not a child of TVEpisode, it is a child of
ParentalControl.

Here is my suggestion:

# Find nodes having a ParentalControl child
for child in root.findall(".//*[ParentalControl]"):
    x = child.find("ParentalControl/Rating").text
    if x == "NC":
        ...

Note that a complete XPath implementation would make that simpler: your
query basically is //*[ParentalControl/Rating=="NC"]

-- Alain.



More information about the Python-list mailing list