我正在使用 Python 和 markup.py 生成一个 XML 文件 ....一切正常,但由于脚本中最近的更改,由于我进行的检查,我现在在节点中得到了重复的值到位。以下是输出示例(它们是车辆记录):
<?xml version='1.0' encoding='UTF-8' ?>
<datafeed>
<vehicle>
<vin>2HNYD18816H532105</vin>
<features>
<feature>AM/FM Radio</feature>
<feature>Air Conditioning</feature>
<feature>Anti-Lock Brakes (ABS)</feature>
<feature>Alarm</feature>
<feature>CD Player</feature>
<feature>Air Bags</feature>
<feature>Air Bags</feature>
<feature>Anti-Lock Brakes (ABS)</feature>
<feature>Alarm</feature>
<feature>Air Bags</feature>
<feature>Alarm</feature>
<feature>Air Bags</feature>
</features>
</vehicle>
<vehicle>
<vin>2HKYF18746H537006</vin>
<features>
<feature>AM/FM Radio</feature>
<feature>Anti-Lock Brakes (ABS)</feature>
<feature>Air Bags</feature>
<feature>Air Bags</feature>
<feature>Anti-Lock Brakes (ABS)</feature>
<feature>Alarm</feature>
<feature>Air Bags</feature>
<feature>Alarm</feature>
</features>
</vehicle>
</datafeed>
这是一个包含 100 多条记录的较大 XML 文件的一小段摘录。我该如何删除重复的节点?
最佳答案
XML 中不存在真正的“重复项”。每个节点的定义都是不同的。但我理解您希望摆脱您的解释中的所有重复功能。
您可以通过简单地解析该树、将特征(节点的值)放入一个集合中(以消除重复项)并写出一个新的 XML 文档来完成此操作。
鉴于您使用 Python 生成文件,您应该修改创建例程,使其一开始就不会生成重复值。您可能想告诉我们 markup.py
是什么或做什么。
编辑
我刚刚快速浏览了标记脚本,因此您的脚本中可能会出现类似的内容:
// well, this might come from somewhere else, but I guess you have such a list somewhere
features = [ 'AM/FM Radio', 'Air Conditioning', 'Anti-Lock Brakes (ABS)', 'Alarm', 'CD Player', 'Air Bags', 'Air Bags', 'Anti-Lock Brakes (ABS)', 'Alarm', 'Air Bags', 'Alarm', 'Air Bags' ]
// write the XML
markup.features.open()
markup.feature( features )
markup.features.close()
在这种情况下,只需在将功能传递给标记脚本之前将其设置为集
即可:
// write the XML
markup.features.open()
markup.feature( set( features ) )
markup.features.close()
如果您有多个单独的列表,其中包含单个车辆的功能,请首先合并这些列表(或组):
list1 = [...]
list2 = [...]
list3 = [...]
features = set( list1 + list2 + list3 )
关于python - 删除 XML 中的重复节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4134531/