解析xml谷歌日历事件



我正试图从这个url解析谷歌日历事件: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,

我得到了一个异常,可能是因为value为null,实际上我需要得到valueString attribue值(例如本例中的"Somewhere")

<gd:where valueString='Somewhere'/>

'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")

<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")
       };

(这是根据一些文档对命名空间进行有根据的猜测。不过,你应该对照你的实际提要进行检查。)

感谢您的帮助,它可以使用以下简单代码:

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

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

最新更新