【问题标题】:How query xml element using linq whether or not the element is existed C#如何使用linq查询xml元素是否存在C#
【发布时间】:2017-09-13 11:51:18
【问题描述】:

我正在尝试从我的本地计算机循环访问几个具有相同格式的 XML 文件,但有些文件缺少图像元素。当循环到达缺少元素的文件时,程序在选择新时崩溃。

XML:

<?xml version="1.0" encoding="UTF-8"?>
<node>
    <id>1663</vid>

    <title>My Title</title>

    <body>
    <und keys="1">
        <n0>
            <value>123 Street</value>
            <summary></summary>
            <format type="NULL"></format>
            <safe_value>123 Street</safe_value>
            <safe_summary></safe_summary>
        </n0>
    </und>
    </body>
   <field keys="1"></field>
   <image>
       <und keys="1">
            <i0>     
                <uri>https://uei.jpg</uri>     
            </i0>
            <i1>
                <uri>https://myurl.jpg</uri>     
            </i1>
        </und>
    </image>
</node>

Linq C# (WPF) 应用程序:

XDocument document = XDocument.Load(file);
var nodes = from b in document.Descendants("node")
            let imgs = b.Element("image")
            select new
            {
                ID = (string)b.Element("id").Value,
                Title = (string)b.Element("title").Value,
                StreetName = (string)b.Element("body").Element("und").Element("n0").Element("value").Value,
                Images = imgs.Descendants("und").ToList()
            };

【问题讨论】:

    标签: c# wpf linq


    【解决方案1】:

    我想它是因为硬演员而崩溃的?

    尝试使用保存转换和空条件运算符 (?.) 这将阻止 NullreferenceExceptions:

    XDocument document = XDocument.Load(file);
    var nodes = from b in document.Descendants("node")
                let imgs = b.Element("image")
                select new
                {
                    ID = b.Element("id")?.Value as string,
                    Title = b.Element("title")?.Value as string,
                    StreetName = b.Element("body")?.Element("und")?.Element("n0")?.Element("value")?.Value as string,
                    Images = imgs?.Descendants("und")?.ToList()
                };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      相关资源
      最近更新 更多