C# 在Windows应用商店应用程序中使用HtmlAgility pack
在我的Windows应用商店应用程序中,我有以下代码来提取id=pos\u 0的divC# 在Windows应用商店应用程序中使用HtmlAgility pack,c#,xpath,windows-store-apps,html-agility-pack,C#,Xpath,Windows Store Apps,Html Agility Pack,在我的Windows应用商店应用程序中,我有以下代码来提取id=pos\u 0的div HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); doc.LoadHtml(my_html_string); var div_i_need = doc.DocumentNode.Descendants("div").Where(x => x.Attributes.Contains("id") &&
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(my_html_string);
var div_i_need = doc.DocumentNode.Descendants("div").Where(x => x.Attributes.Contains("id") && x.Attributes["id"].Value == "pos_0").FirstOrDefault();
有没有更简单的方法?SelectSingleNode在此版本的库中不存在,而且子体似乎不接受XPath,因为.NET没有针对Windows应用商店的XPath实现,所以HtmlAgilityPack无法执行XPath查询。通过使用GetAttributeValue方法,您的代码可以稍微简化,并去掉其中的:
GetAttributeValue返回第二个参数,如果找不到该属性您可以用firstOrDefaults替换Where,这似乎是一个很好的答案。这不是我想要的——因为没有xpath实现,有点恼人——但是你能做什么呢!
var div_i_need = doc.DocumentNode
.Descendants("div")
.FirstOrDefault(x => x.GetAttributeValue("id", "") == "pos_0");