我正在尝试从此网址解析Google日历活动: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'/>
答案 0 :(得分:2)
&#39; GD&#39;看起来像一个命名空间,看看如何在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")
答案 1 :(得分: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 :(得分:2)
感谢您的帮助,它适用于这个简单的代码:
//Where = entry.Elements().First(i => i.Name.LocalName == "where").Value,
Where = entry.Elements().First(i => i.Name.LocalName == "where").Attribute("valueString").Value,
稍后我会尝试实施您的建议以获得更好的代码实现;)