dts*_*tsg 4 c# xml error-handling linq-to-xml
做这样的事情是否有更好的方法:
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
Run Code Online (Sandbox Code Playgroud)
从XML文档解析元素/属性值时?在某些情况下,在执行以下操作时可能找不到该元素:
string foo (string)elem.Element("fooelement").Attribute("fooattribute").Value
Run Code Online (Sandbox Code Playgroud)
因此会发生对象引用错误(假设未找到元素/属性).尝试访问元素值时相同
我只想使用扩展方法.它是一样的,但它更漂亮:
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);
}
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
string foo = element.SafeElement("fooelement").SafeAttribute("fooattribute").Value;
Run Code Online (Sandbox Code Playgroud)