Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple text nodes in Python's ElementTree? HTML generation

I'm using ElementTree to generate some HTML, but I've run into the problem that ElementTree doesn't store text as a Node, but as the text and tail properties of Element. This is a problem if I want to generate something that would require multiple text nodes, for example:

<a>text1 <b>text2</b> text3 <b>text4</b> text5</a>

As far as I can tell there is no way to generate this- am I missing something? Or, is there a better solution for quick and simple HTML generation in Python?

like image 864
Rob Lourens Avatar asked Jun 29 '10 21:06

Rob Lourens


1 Answers

To generate the above string with ElementTree you can use the following code. The trick to this is that the text is the very first lot of text before the next element and the tail is all the text after the element up to the next element.

import xml.etree.ElementTree as ET
root = ET.Element("a")
root.text = 'text1 ' #First Text in the Element a
b = ET.SubElement(root, "b")
b.text = 'text2' #Text in the first b
b.tail = ' text3 ' #Text immediately after the first b but before the second
b = ET.SubElement(root, "b")
b.text = 'text4'
b.tail = ' text5'
print ET.tostring(root)
#This prints <a>text1 <b>text2</b> text3 <b>text4</b> text5</a>
like image 98
Andrew Cox Avatar answered Sep 16 '22 15:09

Andrew Cox