NullException XML Parsing

本文关键字:Parsing XML NullException | 更新日期: 2023-09-27 18:33:10

我在 C# 中解析 XML 时遇到问题,我的 XML 文件如下所示:

<xml>
    <category>books</category>
    <id>1</id>
    <title>lemony</title>
    <sub>
        <title>lemonyauthor</title>
    </sub>
</xml>
<xml>
    <category>comics</category>
    <id>2</id>
    <sub>
        <title>okauthor</title>
    </sub>
</xml>

如您所见,有时会返回"XML"中的标题,有时不会。

我在 C# 中解析此的代码如下所示:

string _Title;
foreach (XElement str in xmlDoc.Descendants("xml"))
{
    _Title = "";
        if (str.Element("title").Value != null)
            _Title = str.Element("title").Value;
        foreach (XElement cha in str.Descendants("sub"))
        {
            if (_Title.Length < 1 && cha.Element("Title").Value != null)
                    _Title = cha.Element("title").Value;
        }
}

如何防止线路if (str.Element("category").Value != null)返回NullException

使用trycatch是唯一的方法吗?

NullException XML Parsing

如果您期望str.Element("title")(这是异常的最可能原因)为空(无论偶尔如何),那么您应该

对此进行测试:
if (str.Element("title") != null)
{
    // your existing code.
}

如果您不希望它为 null,并且确实是一种特殊情况,那么尝试捕获是阻止方法崩溃的唯一其他方法。

更改以下内容:

if (str.Element("title").Value != null)
    _Title = str.Element("title").Value;

对此:

var titleElement = str.Element("title");
if (titleElement != null)
    _Title = titleElement.Value;