Easy way to compare two XMLs for equality

The first thing to do is normalize to two XMLs, for this you can use a small method using Linq:

 

private static XElement Normalize(XElement element)

{

    if (element.HasElements)

    {

        return new XElement(

            element.Name,

            element.Attributes()

            .OrderBy(a => a.Name.ToString()),

            element.Elements().OrderBy(a => a.Name.ToString())

            .Select(e => Normalize(e)));

    }

 

    if (element.IsEmpty)

    {

        return new XElement(element.Name, element.Attributes()

            .OrderBy(a => a.Name.ToString()));

    }

 

    return new XElement(element.Name, element.Attributes()

        .OrderBy(a => a.Name.ToString()), element.Value);

}

 

After both elements were normalized, simply you can compare both strings:

 

bool equal = Normalize(expected).ToString() ==

             Normalize(actual).ToString();

 

A nice place to use this is in unit tests, where you can do your own XML assert class:

 

public static class XmlAssert

{

    public static void AreEqual(

        XElement expected,

        XElement actual)

    {

        Assert.AreEqual(

            Normalize(expected).ToString(),

            Normalize(actual).ToString());

    }

 

    private static XElement Normalize(XElement element)

    {

        if (element.HasElements)

        {

            return new XElement(

                element.Name,

                element.Attributes()

                       .OrderBy(a => a.Name.ToString()),

                element.Elements()

                       .OrderBy(a => a.Name.ToString())

                       .Select(e => Normalize(e)));

        }

 

        if (element.IsEmpty)

        {

            return new XElement(

                element.Name,

                element.Attributes()

                       .OrderBy(a => a.Name.ToString()));

        }

 

        return new XElement(element.Name, element.Attributes()

            .OrderBy(a => a.Name.ToString()), element.Value);

    }

}

Published Friday, January 02, 2009 12:44 AM by marianor
Filed under: ,

Comments

# re: Easy way to compare two XMLs for equality

Monday, March 02, 2009 7:01 AM by Imesh

This is for the comparison of values.

What if we do need to compare the structure of two xmls.

# re: Easy way to compare two XMLs for equality

Tuesday, March 17, 2009 5:03 PM by marianor

It compares structure well, but not schema sequence or node order.

Leave a Comment

(required) 
(required) 
(optional)
(required)