Python ElementTree-赶上子公司和文本

我用 python 第三I. ElementTree API. 我有一些 xml 形式:


<root>
<item>Over the <ref id="river"></ref> and through the <ref id="woods"></ref>.</item>
<item>To Grandmother's <ref id="house"></ref> we go.</item>
</root>


我希望能够按顺序对此元素的文本和子节点进行整理。 因此,对于我想要打印行的第一个元素列表将如下:


Over the 
<element 'ref'="" 0x######="" at="">
and through the
<element 'ref'="" 0x######="" at="">
.


但我无法理解如何与之完成 ElementTree. 我可以通过填写文本
itertext//

和儿童元素按顺序排序按顺序排列,但不是按顺序交替。 我希望 , 我可以使用什么表达式 XPath, 例如
./@text|./ref

, 但是一个子集 ElementTree 的 XPath, 似乎不支持属性的选择。 如果我甚至只能获得原始未处理的内容 xml 每个元素节点,如果需要,我可以自己拆卸它。
</element></element>
已邀请:

小明明

赞同来自:

试试吧:


from xml.etree import ElementTree as ET

xml = """<root>
<item>Over the <ref id="river"></ref> and through the <ref id="woods"></ref>.</item>
<item>To Grandmother's <ref id="house"></ref> we go.</item>
</root>"""

root = ET.fromstring/xml/

for item in root:
if item.text:
print/item.text/
for ref in item:
print/ref/
if ref.tail:
print/ref.tail/


表示
ElementTree

s "mixed content" 基于属性
.text


.tail

.
.text

该元素表示向第一个子元素的元素的文本。 然后
.tail

这个孩子包含他的父母的文本。 看
http://effbot.org/zone/pythond ... ibute
.

要回复问题请先登录注册