Skip to content

Instantly share code, notes, and snippets.

@CGaskell
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CGaskell/8913779 to your computer and use it in GitHub Desktop.
Save CGaskell/8913779 to your computer and use it in GitHub Desktop.
XElementHelper Safely read and cast values provided through the System.Xml.Linq.XElement
namespace DetangledDigital.Services.Helpers
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
// @CGASKELL: Some XElement helpers to assist with safely reading XML
public static class XElementHelper
{
public static T ChildNodeValue<T>(this XElement element, string nodeName)
{
if (element == null || element.Element(nodeName) == null || string.IsNullOrWhiteSpace(element.Element(nodeName).Value))
return default(T);
return (T)Convert.ChangeType(element.Element(nodeName).Value, typeof(T));
}
public static List<int> ChildNodeValueAsListOfIntegers(this XElement element, string nodeName)
{
if (element == null || element.Element(nodeName) == null || string.IsNullOrWhiteSpace(element.Element(nodeName).Value))
return new List<int>();
var stringArray = element.Element(nodeName).Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
if (!stringArray.Any())
return new List<int>();
int parsed = 0;
return stringArray.Where(x => int.TryParse(x, out parsed)).Select(x => parsed).ToList();
}
public static T AttributeValue<T>(this XElement element, string attributeName)
{
if (element == null || element.Attribute(attributeName) == null)
return default(T);
return (T)Convert.ChangeType(element.Attribute(attributeName).Value, typeof(T));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment