c# - 如何处理 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;
}
我想要的是在发生这种情况时获得一个空值或“未指定”,但我不知道如何以一种好的方式做到这一点。我能想到的只是尝试捕获每个变量,但这似乎很复杂。
我怎样才能很好地处理这些案件?
解决方案
使用空检查 - ?
p.Element("name")?.Value,
p.Element("author")?.Value,
p.Element("genre")?.Value,
p.Element("format")?.Value");
推荐阅读
- node.js - Socket.io 与 Firebase 主机上的客户端和 Heroku 上的服务器
- c# - Jenkins Freestyle 构建中 MSbuild 中的解决方案路径错误
- ruby-on-rails - 更改前面没有属性名称的验证消息
- java - 为什么 PrintWriter.println() 在写入 HTML 时不终止行?
- esp32 - 如何让 ESP32 与 Google 表通信
- javascript - 如何从一系列在 javascript 中充当行和列的数组中找到所有排列?
- c++ - 更改对象向量的对象时,值会不断重置
- selenium-webdriver - 在 Protractor 和 Selenium webdriver 中,如何获取已复制到剪贴板的文本?
- csv - csv 阅读器发现的行数少于 bufio 扫描仪
- testing - testcafe:报告任何断言失败的页面 HTML