我有一个具有以下内容的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来实现这一点?
发布于 2016-02-20 19:02:44
首先,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']https://stackoverflow.com/questions/35526724
复制相似问题