我一直在使用LINQ to XML,但遇到了一个问题。我真的很感谢任何人的帮助。我是LINQ to XML的新手,但我发现它很容易使用。
我有两个不同的联合提要,我使用Union将它们聚合为一个单独的联合提要。最终的联合提要包含10个项目。
我正在尝试使用XDocument和XElement将联合提要写成XML文件。在很大程度上,我已经能够成功地做到这一点。但是,提要中的一些项没有作为节点元素的描述。当我到达没有这个node元素的项目时,我得到了一个异常,因为我没有其中一个项目的描述节点。在开始编写XML文件之前,如何检查这些项以查看是否存在名为description的节点?如果该项目不包含description节点,我如何使用默认值填充它?你能给我建议一些解决方案吗?感谢您花了这么多时间!
SyndicationFeed combinedfeed = new SyndicationFeed(newFeed1.Items.Union(newFeed2.Items).OrderByDescending(u => u.PublishDate));
//save the filtered xml file to a folder
XDocument filteredxmlfile = new XDocument(
new XDeclaration("2.0", "utf-8", "yes"),
new XElement("channel",
from filteredlist in combinedfeed.Items
select new XElement("item",
new XElement("title", filteredlist.Title.Text),
new XElement("source", FormatContent(filteredlist.Links[0].Uri.ToString())[0]),
new XElement("url", FormatContent(filteredlist.Links[0].Uri.ToString())[1]),
new XElement("pubdate", filteredlist.PublishDate.ToString("r")),
new XElement("date",filteredlist.PublishDate.Date.ToShortDateString()),
// I get an exception here as the summary/ description node is not present for all the items in the syndication feed
new XElement("date",filteredlist.Summary.Text)
)));
string savexmlpath = Server.MapPath(ConfigurationManager.AppSettings["FilteredFolder"]) + "sorted.xml";
filteredxmlfile.Save(savexmlpath);
发布于 2012-02-11 04:23:55
只需检查null
new XElement("date",filteredlist.Summary !=null ? filteredlist.Summary.Text : "default summary")
https://stackoverflow.com/questions/9237770
复制相似问题