[英]How can i check if this XElement is not null before adding it to an anonymous object?
我正在從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")
確實具有值。 我敢肯定這個問題已經解決過,但是我看不到該怎么辦。 有任何想法嗎?
只需添加一個空檢查。 (下面的代碼應該是一個很好的測試者。有一個有注釋者,有一個沒有注釋者)
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()
};
未經測試...
怎么樣:
XElement xe = doc.Elements("Commentary").FirstOrDefault();
Commentary = xe == null ? null :
select new { ....snip....
我用 ? 運算符,這種方式可以防止生成XMLElement:
例:
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)
...)
},
...);
在這種情況下,如果XElement涉及的對象為null,則不會生成XElement。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.