如何在C#中比较XML字符串?

时间:2012-06-30 02:23:51

标签: c# .net xml linq-to-xml

在DB中,我将XML字符串存储在一列中。下面是我的XML结构:

<?xml version="1.0"?>
-<ProductAttributes xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
-<Attribute Required="false" ID="2" Name="Color">
<Value ID="18">Light Pink</Value>
</Attribute>
-<Attribute Required="false" ID="1" Name="Size">
<Value ID="9">XL</Value>
</Attribute>
</ProductAttributes>

另一种XML是:

<?xml version="1.0"?>
-<ProductAttributes xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
-<Attribute Required="false" ID="1" Name="Size">
<Value ID="1">S</Value>
</Attribute>
-<Attribute Required="false" ID="2" Name="Color">
<Value ID="4">Red</Value>
</Attribute>
-<Attribute Required="false" ID="3" Name="Weight">
<Value ID="6">10gr</Value>
</Attribute>
</ProductAttributes>

备注

  1. 可以有 n 个xml字符串,每个xml字符串可以有 m 个标记

  2. 属性节点可以按不同的顺序排列,例如在第一个属性中,Id = 1可以是第一个属性,在第二个属性中,Id = 1可以是最后一个。

  3. 要求不是比较这些n个XML字符串并查找是否有任何字符串具有完全重复的属性(此比较将考虑值,因为顺序可能不同)。

    请指导和帮助我。

3 个答案:

答案 0 :(得分:1)

不要比较XML的字符串。使用它们作为XML解析器的输入,将它们转换为XML树,然后在树中搜索匹配的元素并比较它们的属性列表。

答案 1 :(得分:1)

您可以尝试The XML Diff and Patch GUI Tool,可以从here下载。我之前使用过它并且工作正常。

答案 2 :(得分:1)

您可以迭代xml doc A的所有节点,并且对于每个节点,在xml doc B中查找其xpath。如果找不到任何路径或找到路径但值不同,则doc不是相同的”。

然后,您必须对B中的所有节点执行相同操作,检查A中的x路径,以确保“B中没有”但A中没有“

一旦找不到xpath或值不匹配,就通过退出优化为“不相等”。