如何纠正linqXml中的处理异常?

How to correct processing exceptions in linqXml?

我在 C# 中使用 Linq xml,但是当某些元素为 null 时,我不知道如何纠正处理异常。 例如,我需要获取属性的一些值,但是这个属性可以为空,或者路径的某部分可以为空。我喜欢这样:

public static string GetImage(this HtmlNode element)
    {
        var result = "";
        try
        {
            return result = element.Element("div").Element("a").Element("img")?.GetAttribute("src").Value;
        }
        catch (Exception)
        {
            return result;
        }
    }

也许我可以轻松搞定? 谢谢回答。

如果您已经在使用 C# 6.0,请像在 Element("img"):

之后一样使用 null conditional operators
return element?.Element("div")?.Element("a")?.Element("img")?.GetAttribute("src")?.Value;