【问题标题】:Getting all nested children within xml tag in python在python中的xml标签中获取所有嵌套的孩子
【发布时间】:2016-02-20 17:39:37
【问题描述】:

我有一个包含以下内容的 xml.etree.ElementTree 对象。

<html>
 <body>
  <c>
   <winforms>
    <type-conversion>
     <opacity>
     </opacity>
    </type-conversion>
   </winforms>
  </c>
 </body>
</html>
<html>
 <body>
  <css>
   <css3>
    <internet-explorer-7>
    </internet-explorer-7>
   </css3>
  </css>
 </body>
</html>
<html>
 <body>
  <c>
   <code-generation>
    <j>
     <visualj>
     </visualj>
    </j>
   </code-generation>
  </c>
 </body>
</html>

我想获取每个 body 标签对中的所有标签。 例如,对于上面的例子,我想要的输出是:

c, winforms, type-conversion, opactiy
css, css3, internet-explorer-7
c, code-generation,j, visualj 

如何在 python 中使用 BeautifulSoup 或 ElementTree XML API 做到这一点?

【问题讨论】:

  • 请发布您的代码。
  • 我无法编码。上面提到的xml数据是xml.etree.ElementTree对象的形式。我想知道是否有一个函数xmltreeobject.functionName() 可以返回给定根节点的所有嵌套子节点。
  • 这不是一个有效的 xml 文档,看起来像多个文档组合在一起,所以大概有一个外部标签包装了所有这些 xml 文档。您可能正在寻找ElementTree.findall(),它采用查找所有元素的路径,例如root.findall('html/body')root.findall('.//body') [任何深度] 将返回所有 body 标记(假设所有 xml 文档的包装标记)。

标签: python xml beautifulsoup elementtree


【解决方案1】:

首先,XML 规范只允许文档中有一个根元素。如果那是您的实际 XML,那么您需要在解析之前用临时根元素包装它。

现在,有了格式良好的 XML,您可以使用 xml.etree 进行解析,并使用简单的 XPath 表达式 .//body//* 来查询 &lt;body&gt; 元素内的所有元素,无论是直接子元素还是嵌套元素:

from xml.etree import ElementTree as et

raw = '''xml string as posted in the question'''
root = et.fromstring('<root>'+raw+'</root>')

target_elements = root.findall('.//body/*')

result = [t.tag for t in target_elements]
print result
# output :
# ['c', 'winforms', 'type-conversion', 'opacity', 'css', 'css3', 'internet-explorer-7', 'c', 'code-generation', 'j', 'visualj']

【讨论】:

    猜你喜欢
    • 2011-09-05
    • 2021-07-04
    • 1970-01-01
    • 2018-07-01
    • 2018-10-06
    • 2022-11-25
    • 2018-04-27
    • 1970-01-01
    • 2015-05-31
    相关资源
    最近更新 更多