Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 529419
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T09:05:24+00:00 2026-05-13T09:05:24+00:00

The following code compares two XML texts and returns a collection of data changes

  • 0

The following code compares two XML texts and returns a collection of data changes between them.

This code works fine but needs to be as resource-friendly as possible.

Is there a faster way to do this in LINQ, e.g. without creating the two collections of XElements and comparing each of their fields for differences?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace TestXmlDiff8822
{
    class Program
    {
        static void Main(string[] args)
        {
            XDocument xdoc1 = XDocument.Parse(GetXml1());
            XDocument xdoc2 = XDocument.Parse(GetXml2());

            List<HistoryFieldChange> hfcList = GetHistoryFieldChanges(xdoc1, xdoc2);

            foreach (var hfc in hfcList)
            {
                Console.WriteLine("{0}: from {1} to {2}", hfc.FieldName, hfc.ValueBefore, hfc.ValueAfter);  
            }

            Console.ReadLine();
        }

        static public List<HistoryFieldChange> GetHistoryFieldChanges(XDocument xdoc1, XDocument xdoc2)
        {
            List<HistoryFieldChange> hfcList = new List<HistoryFieldChange>();

            var elements1 = from e in xdoc1.Root.Elements()
                           select e;

            var elements2 = from e in xdoc2.Root.Elements()
                           select e;

            for (int i = 0; i < elements1.Count(); i++)
            {
                XElement element1 = elements1.ElementAt(i);
                XElement element2 = elements2.ElementAt(i);

                if (element1.Value != element2.Value)
                {
                    HistoryFieldChange hfc = new HistoryFieldChange();
                    hfc.EntityName = xdoc1.Root.Name.ToString();
                    hfc.FieldName = element1.Name.ToString();
                    hfc.KindOfChange = "fieldDataChange";
                    hfc.ObjectReference = (xdoc1.Descendants("Id").FirstOrDefault()).Value;
                    hfc.ValueBefore = element1.Value;
                    hfc.ValueAfter = element2.Value;
                    hfcList.Add(hfc);
                }
            }

            return hfcList;
        }

        public static string GetXml1()
        {
            return @"
<Customer>
    <Id>111</Id>
    <FirstName>Sue</FirstName>
    <LastName>Smith</LastName>
</Customer>
";
        }



        public static string GetXml2()
        {
            return @"
<Customer>
    <Id>111</Id>
    <FirstName>Sue2</FirstName>
    <LastName>Smith-Thompson</LastName>
</Customer>
";
        }
    }

    public class HistoryFieldChange
    {
        public string EntityName { get; set; }
        public string FieldName { get; set; }
        public string ObjectReference { get; set; }
        public string KindOfChange { get; set; }
        public string ValueBefore { get; set; }
        public string ValueAfter { get; set; }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T09:05:24+00:00Added an answer on May 13, 2026 at 9:05 am

    You should be able to get all the elements that have different values using a linq join on the element name.

    var name = xdoc1.Root.Name.ToString();
    var id = (xdoc1.Descendants("Id").FirstOrDefault()).Value;
    
    var diff =  from o in xdoc1.Root.Elements()
            join n in xdoc2.Root.Elements() on o.Name equals n.Name
            where o.Value != n.Value
            select new HistoryFieldChange() {
                    EntityName = name,
                    FieldName = o.Name.ToString(),
                    KindOfChange = "fieldDataChange",
                    ObjectReference = id,
                    ValueBefore = o.Value,
                    ValueAfter = n.Value,
            };
    

    One of the advantages to this method is that it’s easy to parallelize for multicore machines, just use PLinq and the AsParallel extension method.

    var diff =  from o in xdoc1.Root.Elements()
            join n in xdoc2.Root.Elements().AsParallel() on o.Name equals n.Name
            where o.Value != n.Value
            ...
    

    Voila, if the query can be parallelized on your computer then PLinq will automatically handle it. This would speed up large documents, but if your documents are small you may get a better speedup by parallelizing the outer loop that calls GetHistoryFieldChanges using something like Parallel.For.

    Another advantage is that you can simply return IEnumerable from GetHistoryFieldChanges, not need to waste time allocating a List, the items will be returned as they’re enumerated, and the Linq query will not be executed until then.

    IEnumerable<HistoryFieldChange> GetHistoryFieldChanges(...)
    

    Here are times for 1M iterations of the original, Yannick’s In-order, and My non-parallel Linq-only implementations. Run on my 2.8ghz laptop with this code.

    Elapsed Orig    3262ms
    All Linq        1761ms
    In Order Only   2383ms
    

    One interesting thing I noticed… Run the code in debug mode and then release mode, it’s amazing how much the compiler can optimize the pure Linq version. I think returning IEnumerable helps the compiler a lot here.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 367k
  • Answers 367k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer This is an interesting little gotcha. It helps if you… May 14, 2026 at 4:51 pm
  • Editorial Team
    Editorial Team added an answer In theory you could use a conditional like if ([label.backgroundColor… May 14, 2026 at 4:51 pm
  • Editorial Team
    Editorial Team added an answer Boost has a variety of auto-pointers, including ones for arrays.… May 14, 2026 at 4:51 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.