replacing xml elements with other elements using lxml

Ultrus owntheweb at
Wed Aug 29 16:56:21 CEST 2007

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

[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>
   <item><contents>Here is some random content.</contents></item>
   <item><contents>Here is some more random content.</contents></item>
<contents>Here is some content.</contents>

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

Any idea on how to do this? So close! Thanks for the help in
advance. :)

More information about the Python-list mailing list