using System; using System.Collections.Generic; using System.Xml.Linq; using System.Xml.XPath; namespace Neo.Afx.ComponentModel { public static partial class Extensions { #region Child /// /// Gets the child element with the given local name ignoring namespaces that may exist. /// /// The container to be queried. /// The local name of the child to be retrieved. /// The child element with the given local name public static XElement Child(this XContainer e, string localName) { return e.XPathSelectElement(string.Format("./*[local-name()='{0}']", localName)); } #endregion #region Children /// /// Gets the children with the given local name ignoring namespaces that may exist. /// /// The container to be queried. /// The local name of the children to be retrieved. /// The children with the given local name public static IEnumerable Children(this XContainer e, string localName) { return e.XPathSelectElements(string.Format("//*[local-name()='{0}']", localName)); } #endregion #region ToBoolean /// /// Returns the element value as a boolean. /// /// The element to be queried. /// The default value if the attribute is not found. /// The string representation of the element value as a boolean. public static bool ToBoolean(this XElement e, bool defaultValue) { return ToBoolean(e, string.Empty, false); } /// /// Returns the attribute value if is given otherwise the element value as a boolean. /// /// The element to be queried. /// The name of the attribute to be retrieved. /// The default value if the attribute is not found. /// The string representation of the attribute value if is given /// otherwise the element value as a boolean. public static bool ToBoolean(this XElement e, string attributeName, bool defaultValue) { if(e == null) { return defaultValue; } var value = string.Empty; if(string.IsNullOrEmpty(attributeName)) { value = e.Value; } var attr = e.Attribute(attributeName); if(attr != null) { value = attr.Value; } bool result; return bool.TryParse(value, out result) ? result : defaultValue; } #endregion #region ToString /// /// Returns the element value. /// /// The element to be queried. /// The default value if the attribute is not found. /// The string representation of the element value. public static string ToString(this XElement e, string defaultValue) { return ToString(e, null, defaultValue); } /// /// Returns the attribute value if is given otherwise the element value. /// /// The element to be queried. /// The name of the attribute to be retrieved. /// The default value if the attribute is not found. /// The string representation of the attribute value if is given /// otherwise the element value. public static string ToString(this XElement e, string attributeName, string defaultValue) { if(e == null) { return defaultValue; } if(string.IsNullOrEmpty(attributeName)) { return e.Value; } var attr = e.Attribute(attributeName); return attr != null ? attr.Value : defaultValue; } #endregion } }