将所有嵌套子项放在python中的xml标记内

时间:2016-02-20 17:39:37

标签: python xml beautifulsoup elementtree

我有一个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 

我如何使用BeautifulSoup或ElementTree XML API在python中执行此操作?

1 个答案:

答案 0 :(得分:0)

首先,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']