首页 文章

解析xml谷歌日历事件

提问于
浏览
0

我正在尝试从此网址解析谷歌日历事件:http://www.google.com/calendar/feeds/amchamlva%40gmail.com/public/full这里是我的代码:

static IEnumerable<Event> getEntryQuery(XDocument xdoc)
    {
        return from entry in xdoc.Root.Elements().Where(i => i.Name.LocalName == "entry")
               select new Event
               {
                   EventId = entry.Elements().First(i => i.Name.LocalName == "id").Value,
                   Published = DateTime.Parse(entry.Elements().First(i => i.Name.LocalName == "published").Value),
                   Title = entry.Elements().First(i => i.Name.LocalName == "title").Value,
                   Content = entry.Elements().First(i => i.Name.LocalName == "content").Value,
                   Where = entry.Elements().First(i => i.Name.LocalName == "gd:where").FirstAttribute.Value,
                   Link = entry.Elements().First(i => i.Name.LocalName == "link").Attribute("href").Value,

               };
    }

using (StreamReader httpwebStreamReader = new StreamReader(e.Result))
            {
                var results = httpwebStreamReader.ReadToEnd();

                XDocument doc = XDocument.Parse(results);

                System.Diagnostics.Debug.WriteLine(doc);

                var myFeed = getEntryQuery(doc);
                foreach (var feed in myFeed)
                {
                    System.Diagnostics.Debug.WriteLine(feed.Content);

                }

            }

它的工作原理几乎没有,除了这个:

Where = entry.Elements().First(i => i.Name.LocalName == "gd:where").FirstAttribute.Value,

我得到一个异常可能是因为它的值为null,实际上我需要获取valueString属性值(例如在这种情况下为'Somewhere')

<gd:where valueString='Somewhere'/>

3 回答

  • 2

    'gd'看起来像一个命名空间,看看如何在LINQ to XML中使用xml命名空间:

    http://msdn.microsoft.com/en-us/library/bb387093.aspx

    http://msdn.microsoft.com/en-us/library/bb669152.aspx

    也许尝试一些类似的东西

    XNamespace gdns = "some namespace here";
    entry.Elements(gdns + "where")
    
  • 2

    <gd:where> 的本地名称只是 where - gd 部分是命名空间别名 .

    而不是使用所有这些 First 调用检查本地名称,如果您只使用正确的完全限定名称,它将更加清晰 . 例如:

    XNamespace gd = "http://schemas.google.com/g/2005";
    XNamespace atom = "http://www.w3.org/2005/Atom";
    
    return from entry in xdoc.Root.Elements(gd + "entry")
           select new Event
           {
               EventId = (string) entry.Element(atom + "id"),
               Published = (DateTime) entry.Element(atom + "published"),
               Title = (string) entry.Element(atom + "title"),
               Content = (string) entry.Element(atom + "content"),
               Where = (string) entry.Element(gd + "where")
               Link = (string) entry.Element(atom + "link")
           };
    

    (这是根据某些documentation对命名空间进行有根据的猜测 . 你应该根据你的实际Feed来检查这个 . )

  • 2

    感谢您的帮助,它适用于这个简单的代码:

    //Where = entry.Elements().First(i => i.Name.LocalName == "where").Value,
       Where = entry.Elements().First(i => i.Name.LocalName == "where").Attribute("valueString").Value,
    

    稍后我会尝试实现您的建议,以实现更好的代码实现;)

相关问题