Monday, March 28, 2011

xdocument question

I have two documents both are similar but I need to find an elegant and efficient way to compare the two files and return the values in Doc #1 that don't exist in Doc #2.

XML Doc #1

      <ids>
        <id>1</id>
        <id>2</id>
        <id>5</id>
        <id>6</id>
        <id>7</id>
        <id>8</id>
        <id>9</id>
       </ids>
    </ids>

XML Doc #2

  <ids>
    <id>1</id>
    <id>2</id>
    <id>7</id>
    <id>8</id>
    <id>9</id>
  </ids>

I was thinking about using linq if I could join these two documents on the id field. Is there a better way? I'm looking to return id #s 5 and 6.

From stackoverflow
  • Here is a sample that I know works, I only tried it out with small files (File1.xml had 20 items, File2.xml 8 items).

    XDocument file1Doc = XDocument.Load("File1.xml");
    XDocument file2Doc = XDocument.Load("File2.xml");
    
    IEnumerable<string> file1Elements = from d in file1Doc.Descendants("Id")
                                        select d.Value;
    
    IEnumerable<string> file2Elements = from d in file2Doc.Descendants("Id")
                                        select d.Value;
    
    var difference = file1Elements.Except(file2Elements);
    

    Alternatively, and likely more inline with what you seek is:

    XDocument file1Doc = XDocument.Load("File1.xml");
    XDocument file2Doc = XDocument.Load("File2.xml");
    
    IEnumerable<string> file2Elements = from d in file2Doc.Descendants("Id")
                                        select d.Value;
    
    var x = from include in file1Doc.Descendants("Id")
            where file2Elements.Contains(include.Value) != true
            select include;
    

    You might also find some help looking at 101 LINQ Samples on MSDN.

    Richard C. McGuire : glad I could help

0 comments:

Post a Comment