原子进给读取的另一个测试失败

时间:2012-02-20 08:58:15

标签: c# .net atom-feed

我正在使用此函数public static

    IList<Item> ParseAtom(string url)
    {
        try
        {
            XDocument doc = XDocument.Load(url);

            // Feed/Entry
            var entries = from item in doc.Root.Elements().Where(i => i.Name.LocalName == "entry")
                          select new Item
                          {
                              FeedType = FeedType.Atom,
                              Content = item.Elements().First(i => i.Name.LocalName == "content").Value,
                              Link = item.Elements().First(i => i.Name.LocalName == "link").Attribute("href").Value,
                              PublishDate = ParseDate(item.Elements().First(i => i.Name.LocalName == "published").Value),
                              Title = item.Elements().First(i => i.Name.LocalName == "title").Value
                          };

            return entries.ToList();
        }
        catch
        {
            return new List<Item>();
        }
    }

我使用以下链接 http://localhost/posts.atom/

当我在浏览器中打开该链接时,我会看到指向每个帖子项目的链接列表。

  1. 1 Link 2 Link 3 Link 4 Link
  2. 但是当我用它作为解析网址时,我的程序什么也没有返回。我想自己,我不明白上面的链接实际意味着什么。我真的需要你的任何帮助,为我提供更多关于原子进料的解释,非常感谢你。

    XML由另一个文件创建,该文件以如下格式存储为流

    <Root>
      <Child id=123456>
         <Child1>Child1
         </Child1>  
         <Child2>Child2
         </Child2>  
      </Child>
    </Root>
    

1 个答案:

答案 0 :(得分:2)

强烈怀疑正在抛出异常 - 但你无法分辨,因为你通过返回一个空列表“处理”所有异常而不记录什么是例外或任何类型的诊断。我会亲自删除try / catch:如果出现问题,为什么要隐藏它?如果必须捕获异常,则捕获特定的异常,并记录它们,以便您知道发生了什么。

您的查询也可以大大简化:

XDocument doc = XDocument.Load("atom.xml");
XNamespace ns = "http://www.w3.org/2005/Atom";

var entries = doc.Root
                 .Elements(ns + "entry")
                 .Select(item => new Item
                 {
                      FeedType = FeedType.Atom,
                      Content = (string) item.Element(ns + "content"),
                      Link = (string) item.Element(ns + "link").Attribute("href"),
                      PublishDate = (DateTime) item.Element(ns + "published"),
                      Title = (string) item.Element(ns + "title")
                  };

请注意,如果这些元素不存在,现在将内容和标题设置为null;如果您希望再次使用.Value,则更改为使用PublishDate。通过转换为DateTime?而不是DateTime,您可以获得published的相同行为,显然也是在更改了属性的类型之后。处理缺席链接会稍微困难,但也不会太糟糕 - 让我知道你是否想要一只手。

基本上我怀疑它是一个缺席的元素 - 很可能是XDocument.Load。但是,当您记录(或不捕获)异常时,会更容易找到。

编辑:鉴于您的评论,听起来这与您处理XML的方式完全无关 - 它是加载导致问题的XML。这是吞咽异常很重要的地方......

我不知道在通过WebRequest加载XML时提供凭据的任何方式 - 您可能需要使用WebClientXDocument.Load(Stream)来获取数据,然后使用{{1}}。