知道为什么这个 LINQ to XML 查询给我重复的值吗?
我尝试使用 LINQ to XML 查询从论坛线程中的帖子返回作者列表,但该查询为每个帖子返回相同的作者。
当我像这样单独执行查询时,查询可以正常工作:
var doc = XDocument.Load("http://us.battle.net/wow/en/forum/topic/2267488434");
XNamespace ns = "http://www.w3.org/1999/xhtml";
var posts = doc.Descendants(ns + "div")
.Where(a => a.Attribute("id") != null && a.Attribute("id").Value == "thread")
.Elements(ns + "div");
var authors = posts.Descendants().Where(a => a.Attribute("class") != null && a.Attribute("class").Value == "context-link");
但是当我尝试在单个查询中执行相同的操作时,我没有得到相同的结果。以下是我的查询:
var authors = from td in doc.Descendants(ns + "div")
.Where(a => a.Attribute("id") != null && a.Attribute("id").Value == "thread")
.Elements(ns + "div")
let elements = doc.Descendants()
.Where(a => a.Attribute("class") != null)
let author = elements.First(a => a.Attribute("class").Value == "context-link")
select new
{
Author = author.Value.Trim(),
};
知道我做错了什么吗?
I'm trying to return a list of authors from the posts in a forum thread using a LINQ to XML query, but the query is returning me the same author for each post.
The queries work correctly when I do them separately like this:
var doc = XDocument.Load("http://us.battle.net/wow/en/forum/topic/2267488434");
XNamespace ns = "http://www.w3.org/1999/xhtml";
var posts = doc.Descendants(ns + "div")
.Where(a => a.Attribute("id") != null && a.Attribute("id").Value == "thread")
.Elements(ns + "div");
var authors = posts.Descendants().Where(a => a.Attribute("class") != null && a.Attribute("class").Value == "context-link");
But when I try to perform the same action in a single query I am not getting the same results. Below is my query:
var authors = from td in doc.Descendants(ns + "div")
.Where(a => a.Attribute("id") != null && a.Attribute("id").Value == "thread")
.Elements(ns + "div")
let elements = doc.Descendants()
.Where(a => a.Attribute("class") != null)
let author = elements.First(a => a.Attribute("class").Value == "context-link")
select new
{
Author = author.Value.Trim(),
};
Any idea what I'm doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在声明
td
但从未使用它。 的行我怀疑读取
let elements = doc.Descendants()
应该读取
let elements = td.Descendants()
。我认为查询可以更好地写为:
You are declaring
td
but never using it. I suspect that the line that readslet elements = doc.Descendants()
should read
let elements = td.Descendants()
.I think the query could be better written as: