次のコードは、XMLの各要素が「Id」属性を持つ場合にのみ機能します。存在しない属性を無視するようにLINQに指示するにはどうすればよいですか?
ただし、要素にid属性がない場合、LINQはNullReferenceExceptionをスローします。
Id属性がない場合は、空白または空白を割り当てるだけです。
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; }
}
}
(よりよい方法で見つかった - 更新を参照) –