Last active
August 29, 2015 13:56
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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