我想按节点或属性的值比较两个(或更多)XML文件。我对节点名称或属性不感兴趣。
在谷歌上搜索我发现了XMLDiff补丁(http://msdn.microsoft.com/en-us/library/aa302294.aspx),但它对我不起作用..或者我不知道如何让设置为我工作。
FILEA
<Root odata.context="http://services.odata.org/V4/(S(i53ojihzxawmvtyyvztbaelk))/TripPinServiceRW/$metadata">
<value>
<name>Photos</name>
<kind>EntitySet</kind>
<url>Photos</url>
</value>
<value>
<name>People</name>
<kind>EntitySet</kind>
<url>People</url>
</value>
<value>
<name>Airlines</name>
<kind>EntitySet</kind>
<url>Airlines</url>
</value>
<value>
<name>Airports</name>
<kind>EntitySet</kind>
<url>Airports</url>
</value>
<value>
<name>Me</name>
<kind>Singleton</kind>
<url>Me</url>
</value>
<value>
<name>GetNearestAirport</name>
<kind>FunctionImport</kind>
<url>GetNearestAirport</url>
</value>
</Root>
档案B
<Root odata.context="http://services.odata.org/V4/(S(i53ojihzxawmvtyyvztbaelk))/TripPinServiceRW/$metadata">
<value>
<name>Photos</name>
<kind>EntitySet</kind>
<url>Photos</url>
</value>
<value>
<name>People</name>
<kind>EntitySet</kind>
<url>People</url>
</value>
<value>
<name>Airlines</name>
<kind>EntitySet</kind>
<url>Airlines</url>
</value>
<value>
<name>Airports</name>
<kind>EntitySet</kind>
<url>Airports</url>
</value>
<value>
<name>Me</name>
<kind>Singleton</kind>
<url>Me</url>
</value>
<value>
<name>GetNearestAirport</name>
<kind>FunctionImport</kind>
<url>GetNearestAirport</url>
</value>
</Root>
我想验证每个节点或属性的值。 谢谢!
答案 0 :(得分:1)
如果你想这样做你的自己和xml文档的结构是已知的和常量你可以做这样的事情(假设xdocB是有效的文档):
class NodeComparer : IEqualityComparer<XmlNode>
{
public bool Equals(XmlNode x, XmlNode y)
{
if (x == null || y == null)
return false;
if (x.ChildNodes.Count != y.ChildNodes.Count)
return false;
var nodeNames = new [] { "name", "kind", "url" };
for (int i = 0; i < x.ChildNodes.Count; i++)
{
foreach (var nodeName in nodeNames)
{
if (!x[nodeName].InnerText.Equals(y[nodeName].InnerText))
return false;
}
}
// TODO some testing of attributes
return true;
}
public int GetHashCode(XmlNode obj)
{
return 1;
}
}
static void Main(string[] args)
{
XmlDocument xdocA = new XmlDocument();
xdocA.Load(pathA);
XmlDocument xdocB = new XmlDocument();
xdocB.Load(pathB);
var nodesA = xdocA.SelectNodes("Root/value").Cast<XmlNode>();
var nodesB = xdocB.SelectNodes("Root/value").Cast<XmlNode>();
var comp = new NodeComparer();
var errors = nodesA.Where(na => !nodesB.Contains(na, comp));
if (errors.Count() > 0)
{
Console.WriteLine("ERRORS: ");
foreach (var error in errors)
{
Console.WriteLine(string.Join(", ", error.Cast<XmlNode>().Select(xn => $"{xn.Name}: {xn.InnerText}")));
Console.WriteLine();
}
}
else
{
Console.WriteLine("No Errors");
}
Console.ReadLine();
}
}