如何告诉LINQ忽略不存在的属性?

时间:2009-06-04 12:25:12

标签: 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; }
    }
}

1 个答案:

答案 0 :(得分:7)

(第二次编辑)

噢 - 找到了一种更简单的方法;-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
    };

(第1次编辑)

或添加扩展方法:

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")
    };