简体   繁体   中英

how to compare 2 XML using LINQ in C#

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

  1. I have a Name-space in the XML which is obtained from database
  2. The node names are in mixed cases

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

PS 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.

can be done quite easily using Linq to XML or even simple Xml DOM . though i would bravely do it with Regular Expressions . one regex to find all the books, and a couple or so do dismantle each record.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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