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

Tony McDonald tony.mcdonald at ncl.ac.uk
Tue Nov 29 08:38:58 CET 2005


Hi,
I'd like to convert a document (docbook format actually) like this;

<article>
<para>preamble</para>
<para role="book">EMED123</para>
<some
...
<para role="book">RMED789</para>
</article>

(para can be nested)

With something that looks like this
<article>
<para>preamble</para>
<biblioentry>
<title>Human histology</title>
<edition>3rd ed. 2004</edition>
<para >31.99</para>
<author>Stevens,  A &amp; Lowe, J S</author>
...
</biblioentry>

(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>

Which is not what I expected. I expected this;
<doc>
<begin>start</begin>
<replaceme>with something else</replaceme><new>Hi</new>
<end>finish</end>
</doc>

As a first step to replacing my document, but no joy so far...

Can anyone help out here?

cheers
Tone
-- 
Dr Tony McDonald, Asst Director, FMSC. 0191 246 4543
School of Medical Education Development
Project Manager, FDTL-4 ePortfolios http://www.eportfolios.ac.uk/



More information about the XML-SIG mailing list