The following code works but only as long as each element of the XML has an "Id" attribute.
只要XML的每个元素都具有“Id”属性,以下代码就可以工作。
However, if an element does not have an id attribute, LINQ throws an NullReferenceException.
但是,如果元素没有id属性,LINQ会抛出NullReferenceException。
How do I specify that if there is no Id attribute, just assign a null or blank?
如何指定如果没有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 个解决方案
#1
7
(2nd edit)
Ooh - found an easier way ;-p
噢 - 找到了一种更简单的方法;-p
from contentItem in content.Descendants("item")
select new ContentItem
{
Id = (string)contentItem.Attribute("id")
};
This works thanks to the flexible static conversion operators on XAttribute
etc.
这要归功于XAttribute等上灵活的静态转换运算符。
(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")
};
#1
7
(2nd edit)
Ooh - found an easier way ;-p
噢 - 找到了一种更简单的方法;-p
from contentItem in content.Descendants("item")
select new ContentItem
{
Id = (string)contentItem.Attribute("id")
};
This works thanks to the flexible static conversion operators on XAttribute
etc.
这要归功于XAttribute等上灵活的静态转换运算符。
(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")
};