在 python 中获取 xml 标签内的所有嵌套子项

Getting all nested children within xml tag in python

我有一个包含以下内容的 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 或 The ElementTree XML API?

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

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

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