开发者

Any idea why this LINQ to XML query is giving me duplicate values?

开发者 https://www.devze.com 2023-02-18 11:51 出处:网络
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.

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?


You are declaring td but never using it. I suspect that the line that reads

let elements = doc.Descendants()

should read let elements = td.Descendants().

I think the query could be better written as:

var authors =
    from post in doc.Descendants(ns + "div")
    where (string)post.Attribute("id") == "thread"
    select
        (from author in post.Descendants(ns + "div")
         where (string)author.Attribute("class")== "context-link"
         select author.Value.Trim())
        .First();
0

精彩评论

暂无评论...
验证码 换一张
取 消