I want to compare 2 XML files.
My xml1 is:
<ROOT><NODE><BOOK><ID>1234</ID><NAME isbn="dafdfad">Numbers: Language of Science</NAME><AUTHOR>Tobias Dantzig</AUTHOR></BOOK></NODE></ROOT>
I have another XML from database which is
<Book xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><Id>12345</Id><Name isbn="31231223">Numbers: Language of Science</Name><Author>Tobias Dantzig</Author></Book>
I want to compare the "BOOK" node from XML1 and "Book" node from db XML
I want to compare these 2 XML files node by node for Text and attributes value
I am using C# and wanted to know if this is possible using LINQ
Any help would be really appreciated
P.S. I searched for similar posts but couldn't find what i am exactly looking for.
Thanks a lot in advance
Cheers, Karthik
In xml, case and namespace are fundamentally important, and whitespace and attribute-order aren't (making direct string compares incorrect).
So IMO you should parse it; perhaps with XmlSerializer
, but (as you note) both are trivially parsed with LINQ-to-XML:
string xml1 = @"<ROOT><NODE><BOOK><ID>1234</ID><NAME isbn=""dafdfad"">Numbers: Language of Science</NAME><AUTHOR>Tobias Dantzig</AUTHOR></BOOK></NODE></ROOT>";
var book1 = (from book in XElement.Parse(xml1).Elements("NODE").Elements("BOOK")
let nameEl = book.Element("NAME")
select new
{
Id = (int)book.Element("ID"),
Name = nameEl.Value,
Isbn = (string)nameEl.Attribute("isbn"),
Author = (string)book.Element("AUTHOR")
}).Single();
string xml2 = @"<Book xmlns:rdf=""http://www.w3.org/1999/02/22-rdf-syntax-ns#""><Id>12345</Id><Name isbn=""31231223"">Numbers: Language of Science</Name><Author>Tobias Dantzig</Author></Book>";
var el = XElement.Parse(xml2);
var book2 = new
{
Id = (int)el.Element("Id"),
Name = el.Element("Name").Value,
Isbn = el.Element("Name").Attribute("isbn"),
Author = el.Element("Author")
};
Then it is just a case of comparing the values.
An alternative is to use something like xslt to pre-process one of the files to match the expected layout of the other, so you can share parsing code. It depends whether you are already familiar with xslt, I guess.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With