簡體   English   中英

我可以使用ElementTree獲取XML文件的完整結構嗎?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM