【问题标题】:LINQ to XML exception when there is no summary node present不存在摘要节点时的 LINQ to XML 异常
【发布时间】:2012-02-11 04:16:17
【问题描述】:

我一直在使用 LINQ to XML,但遇到了一个问题。我真的很感激任何帮助。我是 LINQ to XML 的新手,但我发现它很容易使用。

我有两个不同的联合供稿,我使用 Union 将它们聚合到一个联合供稿中。最终的联合供稿包含 10 个项目。

我正在尝试使用 XDocument 和 XElement 将联合提要写入 XML 文件。在大多数情况下,我已经能够成功地做到这一点。但是,提要中的某些项目没有作为节点元素的描述。当我到达没有此节点元素的项目时,我得到一个异常,因为我没有其中一个项目的描述节点。在开始编写 XML 文件之前,如何检查项目以查看是否有一个名为 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);

【问题讨论】:

    标签: linq linq-to-xml


    【解决方案1】:

    只需检查null

    new XElement("date",filteredlist.Summary !=null ? filteredlist.Summary.Text : "default summary")
    

    【讨论】:

    • 您好 BorkenGlass,感谢您的回复。我使用了您在上面提供给我的代码,但它给了我一个对象空引用异常。因此,我将其更改为: new XElement("description", filteredlist.Summary.Text != null ? filteredlist.Summary.Text : "default summary") 当我这样做时,它甚至没有在 xml 文件中创建此节点元素.没有例外。我不确定,但我认为在开始编写 xml 文件之前,我需要检查每个联合提要项目中是否存在描述节点。感谢您的宝贵时间!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多