A day with .Net

My day to day experince in .net

LINQ to XML – Null handling by extension method

Posted by vivekcek on November 5, 2012

I am using extension methods to handle blank or null elements in xml processing using LINQ.
My methods are given below.

	private static string isElementNull(this XElement element)
            if (element != null)
                return element.Value;
                return "";

        private static string isAttributeNull(this XElement element, string attributeName)
            if (element == null)
                return "";
                XAttribute attribute = element.Attribute(attributeName);
                return attribute == null ? "" : attribute.Value;

Now how to access element and its attribute in linq.

strng name=q.Element("Name").isElementNull();
string id=q.isAttributeNull("id");

where q is an element.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s