简体   繁体   English

使用python忽略特定属性比较两个xml

[英]Comparing two xml using python ignoring particular attribute

I am looking for a python based solution to compare two xml's ignoring a particular attribute value. 我正在寻找一个基于python的解决方案,以比较忽略特定属性值的两个xml。 For example, the below xml's should be treated as identical though the Ref and ID values are different as these would be different in each xml. 例如,以下xml应该被视为相同,尽管RefID值不同,因为每个xml中的RefID值都不同。 One of the solution could be to substitue these with empty strings first and then compare xml's. 解决方案之一是先用空字符串替换它们,然后比较xml。 Is there any library available in python which can do this while comparing the xmls. python中是否有任何库可以在比较xml时做到这一点。

#XML1:

<Objects>
   <Object Name="Object1" Ref="12345">
        <Item Name="Item1" value="Value1"/>
    </Object>
</Objects>

<RefTable>
    <Refitem ID="12345" Name="Item1"/>
</RefTable>


#XML2:

<Objects>
   <Object Name="Object1" Ref="54321">
        <Item Name="Item1" value="Value1"/>
    </Object>
</Objects>

<RefTable>
    <Refitem ID="54321" Name="Item1"/>
</RefTable>

Something like this could work: 这样的事情可能会起作用:

root1 = etree.fromstring(xml1)
root2 = etree.fromstring(xml2)
for node1, node2 in zip(root1.iter(), root2.iter()):

   if node1.tag == node2.tag:
       a1 = node2.attrib
       a2 = node2.attrib

       if node1.tail != node2.tail:
           raise ValueError('XML differs')

       for ignored in ('ID',):

           try:
              del a1[ignored]
           except AttributeError:
              pass

           try:
              del a2[ignored]
           except AttributeError:
              pass

        if a1 != a2:
           raise ValueError('XML differs')
    else:
        raise ValueError('XML differs')

Instead of izip() you might need to use itertools.izip_longest() 代替izip(),您可能需要使用itertools.izip_longest()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM