python xml.etree.ElementTree get everything inside element whether its text or children
Question: I am using `xml.etree.ElementTree`, and if possible would like not to change
XML parsing library.

I can parse XML file without any problem. I have a speclial `<description>`
tag which contains text and want to retrieve this text. Here is the code I am
using for that purpose:

    
    
    import xml.etree.ElementTree as ET
    rss = ET.fromstring(rss_content)
    for node in rss[0].getchildren():
        if node.tag == 'description':
            print node.text
    

so far, so good. But I sometimes have as text another xml content and can't
retrieve this as a text. I could retrieve this with methods as `getchildren`
and make a switch case whether this is recognized as text or as XML; but I was
wondering if I could directly retrieve the whole content, XML or not, as text,
in a simpler way?


Answer: There is the `itertext()` method on an ElementTree Element - it returns all
the nested text, for example:

    
    
    xmltxt='''<?xml version="1.0"?>
    <TEXT>
        <Description>
            <V>played</V>
            <N>John</N>
            <PREP>with</PREP>
            <en x='PERS'>Adam</en>
            <PREP>in</PREP>
            <en x='LOC'> ASL school</en>
        </Description>
        <Description>
            <V y='0'>went</V>
            <en x='PERS'>Mark</en>
            <PREP>to</PREP>
            <en x='ORG'>United Nations</en>
            <PREP>for</PREP>
            <PREP>a</PREP>
            <N>visit</N>
        </Description>
    
    </TEXT>
    '''
    
    root = ET.fromstring(xmltxt)
    
    for ch in root:
        print ch
        print "".join(ch.itertext())
        print ET.tostring(ch)
    

Output is:

    
    
            played
            John
            with
            Adam
            in
             ASL school
    
    <Description>
            <V>played</V>
            <N>John</N>
            <PREP>with</PREP>
            <en x="PERS">Adam</en>
            <PREP>in</PREP>
            <en x="LOC"> ASL school</en>
        </Description>
    
            went
            Mark
            to
            United Nations
            for
            a
            visit
    
    <Description>
            <V y="0">went</V>
            <en x="PERS">Mark</en>
            <PREP>to</PREP>
            <en x="ORG">United Nations</en>
            <PREP>for</PREP>
            <PREP>a</PREP>
            <N>visit</N>
        </Description>
    

Or to recurse through nested elements, use `iter()` method, collecting .text
for text within the tag, and .tail for text after a tag.

