insert method in ElementTree

Stefan Behnel stefan.behnel-n05pAM at web.de
Sun Jul 16 14:50:48 EDT 2006


mirandacascade at yahoo.com wrote:
> Where I'm struggling is figuring out what the index argument should
> be in the insert method.  Using the example above
> 
> # assume rootElement is the root of the input XML
> xList = rootElement.getiterator()
> idx = 0
> for x in xList:
> 	# mix of pseudo-code and Python code
> 	if (this element has createAnotherWhenCondition attribute)
>                     and
>          (y is true):
> 		jcopy = copy.copy(x)
> 		??.insert(??, jcopy)
> 	idx = idx + 1

ElementTree does not have parent pointers. You have to look one element level
ahead to add the child. You can use a parent stack for this, although
getiterator() is not very helpful in that case as it does not tell you when it
backtracks.

If you want to use lxml instead, you can either
* access the parent directly (element.getparent()) and add the child there
or
* use the iterwalk() function to add the child when backtracking up the tree or
* implement the whole thing in XSLT (with a custom evaluator function in Python).

There may also be other ways to do it. Just give it a try:
http://codespeak.net/lxml/
http://cheeseshop.python.org/pypi/lxml/1.1alpha

Stefan



More information about the Python-list mailing list