【问题标题】:Can I use ElementTree to get the full structure of an XML file?我可以使用 ElementTree 来获取 XML 文件的完整结构吗?
【发布时间】:2015-09-11 02:10:46
【问题描述】:

假设我的 xml 看起来像这样:

<stuff>fee <i>italic</i> fie <b>bold</b> foe</stuff> 

如果我用 ElementTree 解析它,我可以使用 iter() 来访问子元素,我可以使用 itertext() 来访问文本元素,但是我怎样才能同时访问它们呢?换句话说,我想遍历&lt;stuff&gt; 并得到:

text "fee "
element <i>
text " fie "
element <b>
text " foe"

这可能(并且容易),还是我使用了错误的解析器?

【问题讨论】:

  • 您也可以考虑使用.xpath():from lxml import etree / stuff = etree.fromstring('&lt;stuff&gt;fee &lt;i&gt;italic&lt;/i&gt; fie &lt;b&gt;bold&lt;/b&gt; foe&lt;/stuff&gt;') / for node in stuff.xpath("child::node()"): print type(node), node 我意识到这不是通常惯用的 ElementTree 做事方式,而且问题中的案例很简单,我想这并不重要你用的太多了;但是在更复杂的情况下,例如,当您只想选择特定元素或与特定子字符串匹配的特定文本节点时,它可能是获取它们的有效方法

标签: python xml elementtree


【解决方案1】:

您需要获取所有子元素的尾部才能获取内容的所有文本:

>>> 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

【讨论】:

    【解决方案2】:

    这是你要找的吗?

    for e in tree.iter():
      yield e
      try:
         yield e.text
      except:
         continue
    

    【讨论】:

    • 不完全是,但你让我找到了答案;我会在下面发布。
    猜你喜欢
    • 2013-02-13
    • 2010-09-27
    • 1970-01-01
    • 1970-01-01
    • 2010-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多