我正在从XML文件填充匿名对象。到目前为止,
commentary.Elements("Commentator")
总是有一个值,所以我从来没有检查过null。我不得不删除它,现在它在尝试读取该行时失败。
我正在查看代码,但我不知道要改变什么,因为它被选择为匿名对象的属性。
var genericOfflineFactsheet = new
{
Commentary = (from commentary in doc.Elements("Commentary")
select new
{
CommentaryPage = (string)commentary.Attribute("page"),
BusinessName = (string)commentary.Attribute("businessName"),
Commentator = (from commentator in commentary.Elements("Commentator")
select new CommentatorPanel // ASP.NET UserControl
{
CommentatorName = (string)commentator.Attribute("name"),
CommentatorTitle = (string)commentator.Attribute("title"),
CommentatorCompany = (string)commentator.Attribute("company")
}).FirstOrDefault()
}).FirstOrDefault()
问题是,我无法完全删除该行,因为有时候commentary.Elements("Commentator")
会有一个值。我确定此问题已经处理过,但我看不清楚该做什么。有什么想法吗?
答案 0 :(得分:2)
只需添加一个空检查。 (下面的代码应该是一个很好的测试人员。有一个和一个没有评论员)
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XComment("Example"),
new XElement("Commentarys",
new XElement("Commentary",
new XAttribute("page", "2"),
new XAttribute("businessName", "name"),
new XElement("Commentator",
new XAttribute("name", "name"),
new XAttribute("title", "title")
)
)
,
new XElement("Commentary",
new XAttribute("page", "3"),
new XAttribute("businessName", "name2")
)
)
);
var genericOfflineFactsheet = new
{
Commentary = (
from commentary in doc.Elements()
.First().Elements("Commentary")
select new
{
CommentaryPage = (string)commentary.Attribute("page"),
BusinessName = (string)commentary.Attribute("businessName"),
Commentator = (from commentator in commentary.Elements("Commentator")
where commentator != null //<-----you need to add this line
select new // ASP.NET UserControl
{
CommentatorName = (string)commentator.Attribute("name"),
CommentatorTitle = (string)commentator.Attribute("title"),
CommentatorCompany = (string)commentator.Attribute("company")
}
).FirstOrDefault()
}
).FirstOrDefault()
};
答案 1 :(得分:1)
未经测试...
如下:
XElement xe = doc.Elements("Commentary").FirstOrDefault();
Commentary = xe == null ? null :
select new { ....snip....
答案 2 :(得分:1)
答案 3 :(得分:0)
示例:
var xml = new XElement("Root",
myobject == null ? Enumerable.Empty<XElement>() : <= empty IEnumerable if it is null
new [] <= a array with a XElement
{
new XElement("myobject",
new XAttribute("Name", myobject.Name),
new XAttribute("Type", myobject.Type)
...)
},
...);
在这种情况下,如果创建的对象为null,则不会生成XElement。