4 using System
.Collections
;
7 public class XmlComparer
9 public class ComparisonException
: Exception
11 public ComparisonException (string message
)
17 static bool debug
= false;
20 public static void Main (string [] args)
22 if (args.Length < 2) {
23 Console.Error.WriteLine ("Usage: xmldocdiff [reference_output.xml] [actual_output.xml]");
26 if (args.Length > 2 && args [2].EndsWith ("-debug"))
30 Run (args[0], args[1]);
31 } catch (Exception ex) {
32 Console.WriteLine ("FAIL: " + args [1]);
35 Console.WriteLine ("PASS: " + args [1]);
38 public static void Compare (string reference
, string output
)
40 XmlDocument doc1
= new XmlDocument ();
41 doc1
.Load (reference
);
42 XmlDocument doc2
= new XmlDocument ();
45 XmlNodeList memberList1
= doc1
.SelectNodes ("/doc/members/member");
46 XmlNodeList memberList2
= doc2
.SelectNodes ("/doc/members/member");
48 Hashtable namedItems
= new Hashtable ();
50 foreach (XmlElement el
in memberList1
)
51 namedItems
.Add (el
.GetAttribute ("name"), el
);
52 foreach (XmlElement el2
in memberList2
) {
53 string name
= el2
.GetAttribute ("name");
54 XmlElement el1
= namedItems
[name
] as XmlElement
;
56 Report ("Extraneous element found. Name is '{0}'", name
);
59 namedItems
.Remove (name
);
61 CompareNodes (el1
, el2
);
64 foreach (string name
in namedItems
.Keys
)
65 Report ("Expected comment was not found. Name is {0}, XML is {1}", name
, ((XmlElement
) namedItems
[name
]).OuterXml
);
67 // finally, check other nodes than members
68 doc1
.SelectSingleNode ("/doc/members").RemoveAll ();
69 doc2
.SelectSingleNode ("/doc/members").RemoveAll ();
70 string xml1
= doc1
.OuterXml
.Replace ("\r", "").Trim ();
71 string xml2
= doc2
.OuterXml
.Replace ("\r", "").Trim ();
73 Report (@"Either of doc, assembly, name, members elements are different.
75 doc2: {1}", xml1
, xml2
);
78 private static void CompareNodes (XmlNode n1
, XmlNode n2
)
81 Report (@"Nodes does not exist:
82 Node1: {0}", n1
.OuterXml
);
85 if (n1
.NodeType
!= n2
.NodeType
) {
86 Report (@"Nodes differ:
88 Node2: {1}", n1
.OuterXml
, n2
.OuterXml
);
91 if (n1
.Name
!= n2
.Name
) {
92 Report (@"Node names differ:
94 Node2: {1}", n1
.OuterXml
, n2
.OuterXml
);
97 if (n1
is XmlElement
) {
98 for (int i
= 0; i
< n1
.Attributes
.Count
; i
++)
99 CompareNodes (n1
.Attributes
[i
],
101 for (int i
= 0; i
< n1
.ChildNodes
.Count
; i
++)
102 CompareNodes (n1
.ChildNodes
[i
],
105 if (n1
.NodeType
!= XmlNodeType
.Comment
&& n1
.Value
!= null) {
106 string v1
= n1
.Value
.Trim ().Replace ("\r", "");
107 string v2
= n2
.Value
.Trim ().Replace ("\r", "");
109 Report (@"Node values differ:
111 Node2: {1}", v1
, v2
);
115 static void Report (string format
, params object [] args
)
118 Console
.WriteLine (format
, args
);
120 throw new ComparisonException (String
.Format (format
, args
));