如何使用xml.etree.ElementTree关闭python中的一个标签后如何提取嵌套xml中的文本 [英] How to extract text in nested xml after closing of one tag in python using xml.etree.ElementTree
本文介绍了如何使用xml.etree.ElementTree关闭python中的一个标签后如何提取嵌套xml中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想提取xml文档中的所有文本,并且在以下情况下遇到问题:
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>
在此代码段中,我可以得到文本 hello和 there,因为我可以得到它们使用以下标记:
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.
推荐答案
您正在寻找元素的 .tail
属性:
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'
这篇关于如何使用xml.etree.ElementTree关闭python中的一个标签后如何提取嵌套xml中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文