Skip to main content
 首页 » 编程设计

python之如何将 xml 文档拆分为特定标记之间的字符串

2025年05月04日20wuhuacong

假设我有以下 XML:

<foo> 
<spam taste="great"> stuff</spam> <spam taste="moldy"> stuff</spam> 
<bar taste="eww"> stuff </bar> <bar> stuff </bar>  
<bacon taste="yum"> stuff </bacon><bacon taste="yum"> stuff </bacon><bacon taste="yum"> stuff </bacon> 
</foo> 

由于 spam、bar 和 bacon 是内部有更多标签的数据标签,我想将 XML 拆分成这个

  • <spam taste="great"> stuff</spam> <spam taste="moldy"> stuff</spam> ,
  • <bar taste="eww"> stuff </bar> <bar> stuff </bar> ,
  • <bacon taste="yum"> stuff </bacon><bacon taste="yum"> stuff </bacon><bacon taste="yum"> stuff </bacon> ,

为了重新排序以进行解析。

像这样的基本结构, block 的顺序是任意的。

<foo> 
block of bar tags 
block of spam tags 
block of bacon tags 
</foo> 

请您参考如下方法:

如果您不知道运行时标签的名称是什么 + 只想按组分解元素,您可以尝试使用 itertools.groupby结合您想要的任何 xml 解析库:

import xml.etree.ElementTree as et 
import itertools 
 
raw_xml = '''<foo> 
<spam taste="great"> stuff</spam> <spam taste="moldy"> stuff</spam> 
<bar taste="eww"> stuff </bar> <bar> stuff </bar>  
<bacon taste="yum"> stuff </bacon><bacon taste="yum"> stuff </bacon><bacon taste="yum"> stuff </bacon> 
<spam taste="Great">stuff2</spam> 
</foo>''' 
 
groups = itertools.groupby(et.fromstring(raw_xml), lambda element: element.tag) 
groups = [list(group[1]) for group in groups] 
 
print groups 

输出将是:

[[<Element 'spam' at 0x218ecb0>, <Element 'spam' at 0x218ee10>],  
 [<Element 'bar' at 0x218ee90>, <Element 'bar' at 0x218eeb0>],  
 [<Element 'bacon' at 0x218ef30>, <Element 'bacon' at 0x218ef50>, <Element 'bacon' at 0x218ef90>],  
 [<Element 'spam' at 0x218efd0>]] 

如果你需要实际的字符串值,你可以这样做:

print [[et.tostring(element) for element in group] for group in groups] 

...这会让你:

[['<spam taste="great"> stuff</spam> ', '<spam taste="moldy">stuff</spam>\n'], 
 ['<bar taste="eww"> stuff </bar> ', '<bar> stuff </bar> \n'],  
 ['<bacon taste="yum"> stuff </bacon>', '<bacon taste="yum"> stuff </bacon>', '<bacon taste="yum">stuff </bacon>\n'],  
 ['<spam taste="Great">stuff2</spam>\n']]