我有 XML 文件,我只想解析标签,但我需要保留该标签的层次结构和顺序。我曾经xml.etree.ElementTree
这样做过,但我提取了唯一的标签列表。
我的 XML 看起来像:
<Collection variable="value">
<Genre variable="value">
<Timestamp>2017-05-15T18:14:07-05:00</Timestamp>
<Date>2016-12-31</Date>
<Identifier>
<id>123456789</id>
<Name>
<BusinessName>AB & co</BusinessName>
</Name>
</Identifier>
</Genre>
</Collection>
并且所需的输出应该是带有父标签的标签列表
['Collection/Genre',
'Collection/Genre/Timestamp',
'Collection/Genre/Date',
'Collection/Genre/Identifier/id',
'Collection/Genre/Identifier/Name/BusinessName']
任何帮助将不胜感激。
扩展@mzjn 的评论,您可以使用该lxml
包从 ElementTree 中提取路径。此外,作为旁注,与号是 XML 中的保留字符。
from lxml import etree
x = '''<Collection variable="value">
<Genre variable="value">
<Timestamp>2017-05-15T18:14:07-05:00</Timestamp>
<Date>2016-12-31</Date>
<Identifier>
<id>123456789</id>
<Name>
<BusinessName>AB and co</BusinessName>
</Name>
</Identifier>
</Genre>
</Collection>'''
xml = etree.fromstring(x)
tree = xml.getroottree()
paths = [tree.getpath(d) for d in xml.iterdescendants()]
paths
# returns:
['/Collection/Genre',
'/Collection/Genre/Timestamp',
'/Collection/Genre/Date',
'/Collection/Genre/Identifier',
'/Collection/Genre/Identifier/id',
'/Collection/Genre/Identifier/Name',
'/Collection/Genre/Identifier/Name/BusinessName']
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句