Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling null XElements whilst parsing an XDocument

Is there a better way of doing 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 elements/attribute values from an XML document? In some cases the element may not be found when doing something like:

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

So an object reference error would occur (assuming the element/attribute aren't found). Same when trying to access the element value

like image 640
dtsg Avatar asked Dec 25 '22 10:12

dtsg


1 Answers

I would just use extension methods. It's the same thing, but it's prettier:

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);
}

Then you can do:

string foo = element.SafeElement("fooelement").SafeAttribute("fooattribute").Value;
like image 82
Ulf Kristiansen Avatar answered Jan 06 '23 13:01

Ulf Kristiansen