How do I tell LINQ to ignore attributes that don't exist?

The following code works, but only as long as each XML element has an "Id" attribute.

However, if the element does not have an id attribute, LINQ throws a NullReferenceException.

How to indicate that if the Id attribute is missing, just assign a zero or a space?

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; }
    }
}
+3
source share
1 answer

(2nd edit)

Ooh - found an easier way; -p

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

This works thanks to flexible static conversion operators on XAttributeetc.


(original)

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

(1st edit)

Or add an extension method:

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

and use:

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

Source: https://habr.com/ru/post/1709761/


All Articles