Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

p & br using ElementTree?

5 views
Skip to first unread message

Jan Danielsson

unread,
Jun 27, 2007, 12:12:10 AM6/27/07
to
Hello all,

This is probably a mind numbingly brain dead question.. But how do I
generate the following:

<p>Current date:<br/>2000-01-01</p>

..using ElementTree? The <p> element kind of needs two text blocks,
as far as I can tell?

--
Kind regards,
Jan Danielsson

Robert Kern

unread,
Jun 27, 2007, 12:48:38 AM6/27/07
to pytho...@python.org
Jan Danielsson wrote:
> Hello all,
>
> This is probably a mind numbingly brain dead question.. But how do I
> generate the following:
>
> <p>Current date:<br/>2000-01-01</p>
>
> ..using ElementTree? The <p> element kind of needs two text blocks,
> as far as I can tell?

Use the .tail attribute on the br element:

In [1]: from xml.etree import ElementTree as ET

In [4]: p = ET.Element('p')

In [5]: p.text = 'Current date:'

In [6]: br = ET.SubElement(p, 'br')

In [7]: br.tail = '2000-01-01'

In [8]: ET.dump(p)
<p>Current date:<br />2000-01-01</p>

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco

Jan Danielsson

unread,
Jun 27, 2007, 1:12:18 AM6/27/07
to Robert Kern
Robert Kern wrote:
[---]

>> <p>Current date:<br/>2000-01-01</p>
[---]

> Use the .tail attribute on the br element:
>
> In [1]: from xml.etree import ElementTree as ET
>
> In [4]: p = ET.Element('p')
>
> In [5]: p.text = 'Current date:'
>
> In [6]: br = ET.SubElement(p, 'br')
>
> In [7]: br.tail = '2000-01-01'
>
> In [8]: ET.dump(p)
> <p>Current date:<br />2000-01-01</p>

That did the trick. Thanks!

Gabriel Genellina

unread,
Jun 27, 2007, 1:39:52 AM6/27/07
to pytho...@python.org
En Wed, 27 Jun 2007 01:12:10 -0300, Jan Danielsson
<jan.m.da...@gmail.com> escribió:

> This is probably a mind numbingly brain dead question.. But how do I
> generate the following:
>
> <p>Current date:<br/>2000-01-01</p>
>
> ..using ElementTree? The <p> element kind of needs two text blocks,
> as far as I can tell?

No, the date string goes into br's tail:

py> import xml.etree.ElementTree as ET
py> p=ET.fromstring
py> p=ET.fromstring("<p>Current date:<br/>2000-01-01</p>")
py> p
<Element p at b6a850>
py> p.text
'Current date:'
py> p.tail
py> p[0]
<Element br at b6aa58>
py> p[0].text
py> p[0].tail
'2000-01-01'

See <http://effbot.org/zone/element-infoset.htm> about infosets and the
"mixed content" simplified model.

--
Gabriel Genellina

0 new messages