replacing xml elements with other elements using lxml

Stefan Behnel stefan.behnel-n05pAM at web.de
Wed Aug 29 12:44:34 EDT 2007


Ultrus wrote:
> I'm attempting to generate a random story using xml as the document,
> and lxml as the parser. I want the document to be simplified before
> processing it further, and am very close to accomplishing my goal.
> Below is what I have so far. Any ideas on how to move forward?
> 
> The goal:
> read and edit xml file, replacing random elements with randomly picked
> content from within
> 
> Completed:
> [x] read xml
> [x] access first random tag
> [x] pick random content within random item
> [o] need to replace <random> tag with picked contents
> 
> xml sample:
> <contents>Here is some content.</contents>
> <random>
>    <item><contents>Here is some random content.</contents></item>
>    <item><contents>Here is some more random content.</contents></item>
> </random>
> <contents>Here is some content.</contents>

Hmm, this is not well-formed XML, so I assume you stripped the example. The
root element is missing.


> Python code:
> from lxml import etree
> from StringIO import StringIO
> import random
> 
> theXml = "<contents>Here is some content.</
> contents><random><item><contents>Here is some random content.</
> contents></item><item><contents>Here is some more random content.</
> contents></item></random><contents>Here is some content.</contents>"
> 
> f = StringIO(theXml)
> tree = etree.parse(f)

             ^^^^^
This would raise an exception if the above really *was* your input.


> r = tree.xpath('//random')
> 
> if len(r) > 0:
>    randInt = random.randInt(0,(len(r[0]) - 1))
>    randContents = r[0][randInt][0]
>    #replace parent random tag with picked content here
> 
> now that I have the contents tag randomly chosen, how do I delete the
> parent <random> tag, and replace it to look like this:
> 
> final xml sample (goal):
> <contents>Here is some content.</contents>
> <contents>Here is some random content.</contents>
> <contents>Here is some content.</contents>

what about:

   r.getparent().replace(r, random.choice(r))

?

Stefan



More information about the Python-list mailing list