[xml] Rigth way to recursively delete nodes (python/libxml2)



(hope python and libxml2 is on-topic, appologies in advance if it's not)

Hi,

I've started using Python and libxml2, and find it comfortable, once I get
used to it. ;)

I do however worry about picking up too many bad habits, and solving things
the wrong ways.  I'd like to be able to contribute some documentation, but
need my code to be actually resembling correct/clean for that to be useful,
rather than leading others down the path to evil.

One of the things I've had some problems figuring out the RightWay (tm) to
accomplish is the following:


I want to drop any nodes matching or not matching a certain criterium, as well
as it's children.


So far I've come up with something as simple as:

items = mymenu.xpathEval( '//item' )
for i in items:
        if not i.prop('visible'):
                i.unlinkNode()
                i.freeNode()

This would work fine for some situations, but can easily end up trying to free
a node already freed with one of it's parents.

<doc>
        <item>
                <item/>
        </item>
</doc>

Outer <item> would match, both <item>s would get freed, and the code would try
to free the inner <item>, thus creating a nice core dump.


<disclaimer>Yes, I know I could simplify the above by moving the
prop/attribute check to be part of the xpath query, but I'll be adding other
conditional checks, which can't be done in xpath</disclaimer>


Really hoping for some pointers, or someone yelling at me for doing all the
wrong things.  I'll return the favour by wrapping up my python/libxml2
experiences into a nice page once I get a bit more comfortable with it.

Terje




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]