首页 > 解决方案 > 如何处理 XML 元素上的缺失字段

问题描述

我正在尝试将 XML 文件转换为列表。XML 文件包含不同的产品,每个产品都有不同的值,例如:

<product>
    <id></id>
    <name>Commentarii de Bello Gallico et Civili</name>
    <price>449</price>
    <type>Book</type>
    <author>Gaius Julius Caesar</author>
    <genre>Historia</genre>
    <format>Inbunden</format>
</product>
    <product>
    <id></id>
    <name>Katana Zero</name>
    <price>199</price>
    <type>Game</type>
    <platform>PC, Switch</platform>
</product>

问题是有些元素没有所有字段,有些书可能看起来像这样,例如:

<product>
    <id></id>
    <name>House of Leaves</name>
    <price>49</price>
    <type>Bok</type>
    <author>Mark Z. Danielewski</author>
    <genre>Romance</genre>
</product>

当我尝试将这些元素添加到列表中时,它会一直工作,直到我得到一个不包含所有字段的元素。发生这种情况时,我得到“System.NullReferenceException:'对象引用未设置为对象的实例'。”

List<Product> products= new List<Product>();
XElement xelement = XElement.Load(path);
IEnumerable<XElement> pr = xelement.Elements();

foreach (var p in pr)
    {
        switch (p.Element("type").Value)
        {
            case "Book":
                temp.Add(new Book(1, int.Parse(employee.Element("price").Value), 
                    0 , 
                    p.Element("name").Value, 
                    p.Element("author").Value,
                    p.Element("genre").Value, 
                    p.Element("format").Value");
                break;
    }

我想要的是在发生这种情况时获得一个空值或“未指定”,但我不知道如何以一种好的方式做到这一点。我能想到的只是尝试捕获每个变量,但这似乎很复杂。

我怎样才能很好地处理这些案件?

标签: c#xml

解决方案


使用空检查 - ?

p.Element("name")?.Value, 
p.Element("author")?.Value,
p.Element("genre")?.Value, 
p.Element("format")?.Value");

推荐阅读