ElementTree, how to get the whole content of a tag

D

Damjan

Given the folowing XML snippet, I build an ElementTree instance with
et=ElementTree.fromstring(..). Now et.text returns just '\n text\n some
other text'.
Is there any way I could get everything between the <div> and </div> tag?

<div>
text
some other text<br/>
and then some more
</div>
 
F

Fredrik Lundh

Damjan said:
Given the folowing XML snippet, I build an ElementTree instance with
et=ElementTree.fromstring(..). Now et.text returns just '\n text\n some
other text'.
Is there any way I could get everything between the <div> and </div> tag?

<div>
text
some other text<br/>
and then some more
</div>

def gettext(elem):
text = elem.text or ""
for subelem in elem:
text = text + gettext(subelem)
if subelem.tail:
text = text + subelem.tail
return text
'\n text\n some other text\n and then some more\n'

</F>
 
D

Damjan

Is there any way I could get everything between the said:
'\n text\n some other text\n and then some more\n'

I acctually need to get
'\n text\n some other text<br/>\n and then some more\n'

And if there were attributes in <br/> I'd want them too where they were.
Can't I just get ALL the text between the <div> tags?
 
F

Fredrik Lundh

Damjan said:
I acctually need to get
'\n text\n some other text<br/>\n and then some more\n'

that's not the tree content, that's a serialized XML fragment.

the quickest way to do that is to serialize the entire element, and
strip off the start and end tags:

text = ElementTree.tostring(elem)
text = text.split(">", 1)[1].rsplit("<", 1)[0]

alternatively, you can serialize the subelements, and add in properly
encoded text and tail attributes:

def innersource(elem, encoding="ascii"):
text = ElementTree._encode(elem.text or "", encoding)
for subelem in elem:
text = text + ElementTree.tostring(subelem)
if subelem.tail:
text = text + ElementTree._encode(subelem.tail, encoding)
return text

(but _encode is not an official part of the elementtree API, so this code
may not work in post-1.2 releases)

</F>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top