Skip to content

Instantly share code, notes, and snippets.

@CGaskell
Last active Aug 29, 2015
Embed
What would you like to do?
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