編輯:這是我試圖解析的示例XML文檔:http://us.battle.net/wow/en/forum/1011699/(查看源代碼)。LINQ to XML Multiple Selects
這裏有我想要檢索的項目:
- 標題(TBODY/TR/TD/A)
- 作者(TBODY/TR/TD)
- 網址(也存儲在作者節點)
- 日期(TBODY/TR/TD/DIV/DIV)
- 回覆(TBODY/TR/TD)
- 視圖(也存儲在上述節點)
我做了「前查詢」,所以我不必爲遠了每個以下查詢遍歷:
var threads =
from allThreads in xmlThreadList.Descendants(ns + "tbody")
.Descendants(ns + "tr")
.Descendants(ns + "td")
select allThreads;
我代表論壇主題列表的XML文檔。在每個線程中都有不同的孩子,他們擁有我想要檢索的不同信息。目前我通過多次查詢XML文檔來做到這一點。有沒有辦法在單個查詢中提取這些信息並將其存儲在IEnumerable中?我現在這樣做的方式似乎效率低下。
// array of xelements that contain the title and url
var threadTitles =
(from allThreads in threads.Descendants(ns + "a")
where allThreads.Parent.Attribute("class").Value.Equals("post-title")
select allThreads).ToArray();
// array of strings of author names
var threadAuthors =
(from allThreads in threads
where allThreads.Attribute("class").Value.Equals("post-author")
select allThreads.Value.Trim()).ToArray();
// ...
// there are several more queries like this
// ...
// for loop to populate a list with all the extracted data
for (int i = 0, j = 0; i < threadTitles.Length; i++, j++)
{
ThreadItem threadItem = new ThreadItem();
threadItem.Title = threadTitles[i].Value.Trim();
threadItem.Author = threadAuthors[i];
threadItem.Url = Path.Combine(_url, threadTitles[i].Attribute("href").Value);
threadItem.Date = threadDates[i];
threadItem.Replies = threadRepliesAndViews[j++];
threadItem.Views = threadRepliesAndViews[j];
_threads.Add(threadItem);
}
任何意見,將不勝感激。我是全新的LINQ to XML場景。
能否請您提供您正在訪問的XML的例子嗎?請說明您想要提取的信息。 :) – 2011-03-18 14:57:39
我已經發布了一些更多信息,讓我知道如果您需要更多 - 謝謝! – johnhforrest 2011-03-18 15:37:07
你能告訴我們什麼在線程變量? – GreyCloud 2011-03-18 15:37:21