Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts

Tuesday, 7 February 2012

LINQ to XML Enum Extension Method Converter

Below are easy to use extension methods to extract a generic enum from an XML attribute using LINQ to XML:


    
public static class ExtensionMethods
    {
        public static string SafeAttribute(this XElement element, string key)
        {
            var attribute = element.Attribute(key);
            return attribute != null ? element.Attribute(key).Value : "";
        }

        public static T SafeAttribute<T>(this XElement element, string key)
        {
            var attribute = SafeAttribute(element, key);
            return !string.IsNullOrEmpty(attribute) ? (T)Enum.Parse(typeof(T), attribute) : default(T);
        }
    }

Any this is how you would call it:

var xml = XDocument.Load(filePath);
var e = xml.Element("Item").SafeAttribute<MyEnum>("myKey");

Wednesday, 13 May 2009

LINQ to XML

Below is an example of how I used LINQ to XML to read an XML string and search for nodes that match a criteria within the tree. It also shows how I order by an attribute.

The XML:



The Code:


Friday, 27 March 2009

Navigating XElement

The XMl looks like this:




I first create a navigator with an XPath expression to get the nodes set I want to work with:

XElement root = XElement.Load("data.xml");
var answers = root.CreateNavigator().Select("/Category/Subject/Question/Answer");

Then I loop through each answer...

while (answers.MoveNext())
{

Here I convert the underlying object to an Element to get the values:

var details = answers.Current.UnderlyingObject as XElement;

Now I can access the elements I want:

var val = details.Element("Description").Value;

}

Thursday, 29 January 2009

Best way to write XML in C#

This is my opinion the way to create XML within c# - LINQ to XML:

var root =

new XElement("content",

new XAttribute("id", node.Id),

new XAttribute("url", node.NiceUrl),

new XAttribute("title", property != null ? property.Value : node.Name)

);