Created
September 10, 2012 12:43
-
-
Save markrendle/3690696 to your computer and use it in GitHub Desktop.
Maybe extensions for LinqToXML
This file contains 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
public class Person | |
{ | |
public string Name { get; set; } | |
public List<string> Numbers { get; set; } | |
public static Person FromXml(XElement xml) | |
{ | |
return new Person | |
{ | |
Name = xml.Element("Name").MaybeValue(), | |
Numbers = xml.Element("Numbers").MaybeElements("Number").Select(e => e.MaybeValue()).ToList() | |
}; | |
} | |
} |
This file contains 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
public static class XElementExtensions | |
{ | |
public static XElement MaybeElement(this XElement element, XName name) | |
{ | |
if (element == null) return null; | |
return element.Element(name); | |
} | |
public static IEnumerable<XElement> MaybeElements(this XElement element) | |
{ | |
if (element == null) return Enumerable.Empty<XElement>(); | |
return element.Elements(); | |
} | |
public static IEnumerable<XElement> MaybeElements(this XElement element, XName name) | |
{ | |
if (element == null) return Enumerable.Empty<XElement>(); | |
return element.Elements(name); | |
} | |
public static string MaybeValue(this XElement element) | |
{ | |
return element == null ? null : element.Value; | |
} | |
public static string MaybeValue(this XAttribute attribute) | |
{ | |
return attribute == null ? null : attribute.Value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment