我是Xpath的新手,我正在尝试找到我存储在HtmlNodeCollection
更具体地说,我有这个集合:HtmlNodeCollection Results = doc.DocumentNode.SelectNodes("//div[@id = 'SearchResults']//div[@class = 'AdvItemBox']");
在每个"AdvItemBox"
内,有一个div
class='AdvNameHeader'
我让alrady尝试了这段代码,但它不断返回它找到的第一个孩子:
HtmlNodeCollection Results = doc.DocumentNode.SelectNodes("//div[@id = 'SearchResults']//div[@class = 'AdvItemBox']");
StringBuilder strb = new StringBuilder();
foreach (HtmlNode item in Results)
{
HtmlNode itemName = doc.DocumentNode.SelectSingleNode("//div[@id = 'SearchResults']//div[@class = 'AdvItemBox']//div[@class = 'AdvNameHeader']");
strb.AppendFormat("Name: {0}{1}", Regex.Replace(item.InnerText, @"\s+", ""), Environment.NewLine);
}
答案 0 :(得分:2)
使用item
作为循环中查询的起点,并使用相对XPath:
HtmlNodeCollection Results = doc.DocumentNode.SelectNodes("//div[@id = 'SearchResults']//div[@class = 'AdvItemBox']");
StringBuilder strb = new StringBuilder();
foreach (HtmlNode item in Results)
{
HtmlNode itemName = item.SelectSingleNode(".//div[@class = 'AdvNameHeader']");
strb.AppendFormat("Name: {0}{1}", Regex.Replace(item.InnerText, @"\s+", ""), Environment.NewLine);
}