Wednesday 8 June 2011

LinqToXML - Safe element and attribute checking [XElement Extension Method]


When using LINQ with XML, you may run into issues where nodes do not exist, values are empty, attribute are either missing or empty also.

By creating two extension methods for the XElement class, we can provide safe checking for these elements and attributes. Consider the following code snippet below...


Invoking the extension method with LINQ
XDocument contentXML = XDocument.Load(xmlPath);
var res = from x in contentXML.Descendants("rootNode")
orderby x.Element("title").ElementValueNull()
select new TestObject(x.AttributeValueOrDefault("id"), x.Element("title").ElementValueNull());



XElement Extension class
// <copyright file="XElementExtensionMethods.cs" company="GinkoSolutions">
// Copyright (c) 2011 All Right Reserved
// </copyright>
// <author>Sean Greasley</author>
// <email>sean@ginkosolutions.com</email>
// <summary>Extension methods for the XElement class</summary>
namespace XElementTest
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Xml;
    using System.Xml.Linq;
 
    /// <summary>
    /// Extension methods for the XElement class
    /// </summary>
    public static class XElementExtensionMethods
    {
        /// <summary>
        /// Allows a safe way to retrieve attribute values from an element
        /// </summary>
        /// <param name="element">A reference to the element object</param>
        /// <param name="attributeName">The name of the attribute</param>
        /// <returns>The attribute content or null</returns>
        public static string AttributeValueOrDefault(this XElement element, string attributeName)
        {
            XAttribute attr = null;
 
            if (element != null)
                attr = element.Attribute(attributeName);
 
            return attr == null ? null : attr.Value;
        }
 
        /// <summary>
        /// Allows a safe way to retrieve element data
        /// </summary>
        /// <param name="element">A reference to the element object</param>
        /// <returns>Element content or an empty string</returns>
        public static string ElementValueNull(this XElement element)
        {
            if (element != null)
                return element.Value;
 
            return string.Empty;
        }
    }
}

1 comment:

Unknown said...

It worked for me only after I moved the declaration of XElementExtensionMethods to outside of my class. Make it the very first class in your program after using ; statements.