[英]How can i add a full new Element (using ElementTree in Python) to a XML File
[英]Can I use ElementTree to get the full structure of an XML file?
假设我的xml看起来像这样:
<stuff>fee <i>italic</i> fie <b>bold</b> foe</stuff>
如果使用ElementTree对此进行解析,则可以使用iter()
访问子元素,并且可以使用itertext()
访问文本元素,但是如何同时访问它们? 换句话说,我要遍历<stuff>
并得到:
text "fee "
element <i>
text " fie "
element <b>
text " foe"
这可能(且容易),还是我使用了错误的解析器?
这是你想要的?
for e in tree.iter():
yield e
try:
yield e.text
except:
continue
您需要获取所有子元素的尾部以获取内容的所有文本:
>>> import xml.etree.ElementTree as ET
>>> root = ET.fromstring('<stuff>fee <i>italic</i> fie <b>bold</b> foe</stuff>')
>>> print('Text:', root.text)
>>> for child in root:
... print('Element:', child.tag)
... print('Text:', child.tail)
Text: fee
Element: i
Text: fie
Element: b
Text: foe
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.