Zac*_*chS 0 .net c# linq twitter linq-to-xml
我有一个应用程序,我正在编写,允许用户搜索Twitter,主要是为了有趣和学习XML和LINQ如何一起玩.我编写了用于获取原子提要的代码(示例查询:http://search.twitter.com/search.atom?q = towitter),我可以验证它实际上是在接收XML.
为了开始解析文档,我认为只需解析每条推文的内容就足够了.一旦我确认它有效,那么我将转向作者,然后是日期,依此类推,直到解析完所有内容.
以下是我用来获取内容的内容:
var list = from tweet in doc.Element("feed").Descendants("entry")
select new Tweet("AUTHOR", tweet.Element("content").Value, new DateTime(), "TITLE");
Run Code Online (Sandbox Code Playgroud)
如您所见,文档结构如下所示:
<feed><entry><content></content></entry>.....</feed>
Run Code Online (Sandbox Code Playgroud)
至少就我们而言.我在这行代码上得到一个NullReferenceException,但调试器显示该文档不为null(事实上它确实在其中加载了整个feed).上一行调用XDocument.Parse(),它不会抛出异常.
有谁知道什么可能导致我的垮台?
该feed
元素包括:
xmlns="http://www.w3.org/2005/Atom"
Run Code Online (Sandbox Code Playgroud)
这会更改元素的默认命名空间.你应该这样使用:
XNamespace ns = "http://www.w3.org/2005/Atom";
var list = from tweet in doc.Element(ns + "feed")
.Descendants(ns + "entry")
select new Tweet("AUTHOR",
tweet.Element(ns + "content").Value,
new DateTime(), "TITLE");
Run Code Online (Sandbox Code Playgroud)
(只是为了解释,你正在寻找一个没有命名空间的"feed"元素;它不存在,所以Element
返回null.如果你修复了那个,Descendants
就会返回一个空序列.如果你修复了那两个,tweet.Element("content")
会返回null,导致不同 NullPointerException
.)