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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With