删除XML中的重复节点

2024-09-27 22:20:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Python和标记.py……一切都在进行中,但是由于脚本最近的更改,我现在在节点中得到了重复的值,这是因为我进行了适当的检查。以下是输出示例(它们是车辆记录):

<?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文件的一个小片段。如何删除重复节点?在


Tags: lock节点记录absairambagsfeature
1条回答
网友
1楼 · 发布于 2024-09-27 22:20:48

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()

在这种情况下,只需在将特性传递给标记脚本之前将其设为set

^{pr2}$

如果您有多个单独的列表,其中包含单个车辆的功能,请首先合并这些列表(或集合):

list1 = [...]
list2 = [...]
list3 = [...]
features = set( list1 + list2 + list3 )

相关问题 更多 >

    热门问题