c# - 我如何告诉 LINQ 忽略不存在的属性?

标签 c# xml linq

以下代码有效,但前提是 XML 的每个元素都具有“Id”属性。

但是,如果元素没有 id 属性,LINQ 会抛出 NullReferenceException。

如何指定如果没有 Id 属性,则只分配一个 null 或空白?

using System;
using System.Linq;
using System.Xml.Linq;

namespace TestXmlElement2834
{
    class Program
    {
        static void Main(string[] args)
        {

            XElement content = new XElement("content",
                new XElement("item", new XAttribute("id", "4")),
                new XElement("item", new XAttribute("idCode", "firstForm"))
                );

            var contentItems = from contentItem in content.Descendants("item")
                               select new ContentItem
                               {
                                   Id = contentItem.Attribute("id").Value

                               };

            foreach (var contentItem in contentItems)
            {
                Console.WriteLine(contentItem.Id);
            }

            Console.ReadLine();


        }
    }

    class ContentItem
    {
        public string Id { get; set; }
        public string IdCode { get; set; }
    }
}

最佳答案

(第二次编辑)

哦 - 找到了一个更简单的方法;-p

    from contentItem in content.Descendants("item")
    select new ContentItem
    {
        Id = (string)contentItem.Attribute("id")
    };

这要归功于 XAttribute 等灵活的静态转换运算符。


(原创)

    from contentItem in content.Descendants("item")
    let idAttrib = contentItem.Attribute("id")
    select new ContentItem
    {
        Id = idAttrib == null ? "" : idAttrib.Value
    };

(第一次编辑)

或者添加一个扩展方法:

static string AttributeValue(this XElement element, XName name)
{
    var attrib = element.Attribute(name);
    return attrib == null ? null : attrib.Value;
}

并使用:

    from contentItem in content.Descendants("item")
    select new ContentItem
    {
        Id = contentItem.AttributeValue("id")
    };

关于c# - 我如何告诉 LINQ 忽略不存在的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/950210/

相关文章:

c# - 如何使用 AutoFixture 自动生成包含只读列表的对象?

java - 从 Java 读取 XML 字符串

ios - NSXMLParser 不适用于某些标签

c# - Linq 从字符串排序方向

c# - 复杂的 LINQ 分页算法

c# - 使用 AntiForgeryToken 和缓存页面

c# - 如何让 GtkSharp 应用程序在 Windows 上运行

c# - 将字符串与类属性名称匹配

PHP Xml 属性解析

c# - Linq distinct 不调用 Equals 方法