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

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


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

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.


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.


I've got a somewhat similar situation that I'm dealing with like this:

dels = []
for node in tree:
        if shouldbedeleted(node)
for node in dels:

.... which is working OK for me in fairly high volume -- hundreds of calls a day, and no core dumps. But since I am iterating through a tree,
I know I'll always see parents before children, so after dels.reverse()
everything is cool. Don't know if that's the case with an xpath selection.

-- Wade Leftwich
Ithaca, NY

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