Handling Null XElements in XDocument Analysis

Is there a better way to do something like this:

private XElement GetSafeElem(XElement elem, string key)
{
    XElement safeElem = elem.Element(key);
    return safeElem ?? new XElement(key);
}

private string GetAttributeValue(XAttribute attrib)
{
    return attrib == null ? "N/A" : attrib.Value;
}

var elem = GetSafeElem(elem, "hdhdhddh");
string foo = GetAttributeValue(e.Attribute("fkfkf"));

//attribute now has a fallback value

When parsing element / attribute values ​​from an XML document? In some cases, an element cannot be found when doing something like:

string foo (string)elem.Element("fooelement").Attribute("fooattribute").Value

Thus, an object reference error would occur (assuming that the element / attribute was not found). The same thing when trying to access the value of an element

+4
source share
4 answers

Not sure if this is the best approach, but I saw it in a CodeProject post and thought it might be a useful approach.

This is a monadic solution using the "With" extension method:

public static TResult With<TInput, TResult>(this TInput o, 
       Func<TInput, TResult> evaluator)
       where TResult : class where TInput : class
{
  if (o == null) return null;
  return evaluator(o);
}

and return extension method:

public static TResult Return<TInput,TResult>(this TInput o, 
       Func<TInput, TResult> evaluator, TResult failureValue) where TInput: class
{
  if (o == null) return failureValue;
  return evaluator(o);
}

, :

var myElement = element.With(x => x.Element("FooElement")).Return(x => x.Attribute("FooAttribute").Value, "MyDefaultValue")

, , , , IMO

CodeProject - Maybe

+2

. , :

public static XElement SafeElement(this XElement element, XName name)
{
    return element.Element(name) ?? new XElement(name);
}

public static XAttribute SafeAttribute(this XElement element, XName name)
{
    return element.Attribute(name) ?? new XAttribute(name, string.Empty);
}

:

string foo = element.SafeElement("fooelement").SafeAttribute("fooattribute").Value;
+5

# 6.0 Null- ?. :

string foo = elem.Element("fooelement")?.Attribute("fooattribute")?.Value;

fooelement fooattribute , null. " ".

+1

;

public static string TryGetElementValue(this XElement parentEl, string elementName, string defaultValue = null) 
{
    var foundEl = parentEl.Element(elementName);
    if(foundEl != null)
    {
     return foundEl.Value;
    }
else
{
     return defaultValue;
}
}

:

select new News()
                {
                    id = noticia.TryGetElementValue("IdNoticia"),
                    published = noticia.TryGetElementValue("Data"),
                    title = noticia.TryGetElementValue("Titol"),
                    subtitle = noticia.TryGetElementValue("Subtitol"),
                    thumbnail = noticia.TryGetElementValue("Thumbnail", "http://server/images/empty.png")
                };
0
source

Source: https://habr.com/ru/post/1535907/


All Articles