python xml.etree.ElementTree获取元素内部的所有内容,无论是文本还是子元素

时间:2016-01-09 14:36:49

标签: python xml

我正在使用xml.etree.ElementTree,如果可能,我希望不要更改XML解析库。

我可以毫无问题地解析XML文件。我有一个特殊的<description>标记,其中包含文本并想要检索此文本。这是我为此目的使用的代码:

import xml.etree.ElementTree as ET
rss = ET.fromstring(rss_content)
for node in rss[0].getchildren():
    if node.tag == 'description':
        print node.text
到目前为止,这么好。但我有时将另一个xml内容作为文本,并且无法将其作为文本检索。我可以使用getchildren方法检索这个并创建一个切换案例,无论它是被识别为文本还是XML;但我想知道我是否可以以更简单的方式直接检索整个内容,XML或不作为文本?

1 个答案:

答案 0 :(得分:1)

ElementTree元素上有itertext()方法 - 它返回所有嵌套文本,例如:

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)

输出是:

        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>

或者通过嵌套元素进行递归,使用iter()方法,为标记内的文本收集.text,并在标记后收集.tail文本。

相关问题