How to extract text in nested xml after closing of

2019-08-20 15:04发布

I want to extract all text in xml document, and I am having a problem for the following case:

...
<a>
hello
<B>
there
</B>
How was your day.

.....
</a>

In this snippet, I can get the text "hello" and "there" because I can get them using the following tags:

a.text
b.text

but I don't know how to access the "How was your day." part.

1条回答
神经病院院长
2楼-- · 2019-08-20 15:46

You are looking for the .tail attribute of an element:

>>> from xml.etree import ElementTree
>>> example = ElementTree.fromstring('''\
... <a>
... hello
... <B>
... there
... </B>
... How was your day.
... </a>
... '''
... )
>>> example
<Element 'a' at 0x10715d150>
>>> example.text
'\nhello\n'
>>> example.find('B')
<Element 'B' at 0x10715d7d0>
>>> example.find('B').text
'\nthere\n'
>>> example.find('B').tail
'\nHow was your day.\n'
查看更多
登录 后发表回答