/// <summary> /// Adds, removes, or sets an attribute. If <paramref name="value"/> is not null, the /// attribute's value will be <paramref name="value"/> after conversion to string. If the /// value is null and the attribute exists, it is removed. If the value is not null and the /// attribute does not exist, it is added. /// </summary> /// <param name="element"></param> /// <param name="name"></param> /// <param name="value"></param> /// <exception cref="NotSupportedException">The given navigable does not support editing.</exception> public static void SetAttributeValue(this IXPathNavigable element, XName name, object value) { Checker.NotNull(element, "element"); Checker.NotNull(name, "name"); element.GetSelfOrNewElementNavigator().RawSetAttribute(name, (value == null) ? null : value.ToString()); }
/// <summary> /// Retrieves the value of the attribute having the given name, or an empty result if there is no such attribute. /// </summary> /// <param name="element"></param> /// <param name="name"></param> /// <returns></returns> public static Opt <string> AttributeValueOpt(this IXPathNavigable element, XName name) { Checker.NotNull(element, "element"); Checker.NotNull(name, "name"); var nav = element.GetSelfOrNewElementNavigator(); var hasValue = true; var value = nav.RawGetAttribute(name); if (value.Equals(string.Empty)) { // Since an empty string is returned for a missing attribute, we must check whether // the value is absent or simply blank. hasValue = nav.RawHasAttribute(name); } return(Opt.Create(hasValue, value)); }
/// <summary> /// Determines whether this element contains an attribute matching the given XName. /// </summary> /// <param name="element"></param> /// <param name="name"></param> /// <returns></returns> public static bool HasAttribute(this IXPathNavigable element, XName name) { Checker.NotNull(element, "element"); Checker.NotNull(name, "name"); return(element.GetSelfOrNewElementNavigator().RawHasAttribute(name)); }