Compare XElements - CSharp System.Xml

CSharp examples for System.Xml:XML Element

Description

Compare XElements

Demo Code


using System.Xml.Linq;
using System.Reflection;
using System.Linq;
using System;/*from  ww  w.  ja va2 s.co m*/
using MultiDocument.Interfaces;

public class Main{
        public static bool CompareXElements(XElement firstElement, XElement secondElement)
        {
            XElement a = NormalizeElement(firstElement);
            XElement b = NormalizeElement(secondElement);

            return XElement.DeepEquals(a, b);
        }
        private static XElement NormalizeElement(XElement element)
        {
            if (element.HasElements)
            {
                return new XElement(element.Name, element.Attributes().
                    Where(a => a.Name.Namespace == XNamespace.Xmlns).
                    OrderBy(a => a.Name.ToString()), element.Elements().
                    OrderBy(a => a.Name.ToString()).
                    Select(e => NormalizeElement(e)));
            }

            if (element.IsEmpty || string.IsNullOrEmpty(element.Value))
            {
                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);
        }
}

Related Tutorials