[XML-SIG] How do I replace multiple elements in a document? (using ElementTree)

Fredrik Lundh fredrik at pythonware.com
Tue Nov 29 12:47:58 CET 2005


Tony McDonald wrote:

> (biblioentry can be repeated). That is, the original <para
> role="book">EMED123</para> should be totally replaced by the
> biblioentry element(s).
>
> The code EMED123 is used as a key into a database to look up the book
> entries. We then generate biblioentry(s) from it. That works fine,
> and I'm creating Elements from that happily.
>
> What I *cannot* get right is the replacement. I've tried append but
> that seems to work so;
>
> xml = """<?xml version="1.0"?>
> <doc>
> <begin>start</begin>
> <replaceme>with something else</replaceme>
> <end>finish</end>
> </doc>
> """
> root = XML(xml)
> new = Element("new")
> new.text = "Hi"
> elements = root.getiterator()
> for element in elements:
>      if element.tag == 'replaceme':
>          element.append(new)
> dump(root)
>
> Produces this;
> <doc>
> <begin>start</begin>
> <replaceme arg="EMED">with something else derived from <new>Hi</new></
> replaceme>
> <end>finish</end>
> </doc>

how about:

xml = """<?xml version="1.0"?>
<doc>
<begin>start</begin>
<replaceme>with something else</replaceme>
<end>finish</end>
</doc>
"""

root = XML(xml)

new = Element("new")
new.text = "Hi"
new.tail = "\n"

for index, element in enumerate(root):
     if element.tag == 'replaceme':
         root[index] = new
dump(root)

this prints

<doc>
<begin>start</begin>
<new>Hi</new>
<end>finish</end>
</doc>

to do this recursively, you can either put the code in a function
that calls itself, or you can simply add an extra loop:

for parent in root.getiterator():
    for index, element in enumerate(parent):
        if element.tag == 'replaceme':
            parent[index] = new

hope this helps!

</F>





More information about the XML-SIG mailing list