C# 按解析值HTML AgilityPack C分组#
在C#中对数据进行分组,我已经解析了html文件并获取了其中的所有数据,现在我想将它们分组如下: 选择的行是父行,包含以下子行,我正在处理的代码如下:C# 按解析值HTML AgilityPack C分组#,c#,html,xpath,group-by,selectnodes,C#,Html,Xpath,Group By,Selectnodes,在C#中对数据进行分组,我已经解析了html文件并获取了其中的所有数据,现在我想将它们分组如下: 选择的行是父行,包含以下子行,我正在处理的代码如下: var uricontent = File.ReadAllText("TestHtml/Bew.html"); var doc = new HtmlDocument(); // with HTML Agility pack doc.LoadHtml(uricontent);
var uricontent = File.ReadAllText("TestHtml/Bew.html");
var doc = new HtmlDocument(); // with HTML Agility pack
doc.LoadHtml(uricontent);
var rooms = doc.DocumentNode.SelectNodes("//table[@class='rates']").SelectMany(
detail =>
{
return doc.DocumentNode.SelectNodes("//td[@class='rate-description'] | //table[@class='rooms']//h2 | //table[@class='rooms']//td[@class='room-price room-price-total']").Select(
r => new
{
RoomType = r.InnerText.CleanInnerText(),
});
}).ToArray();
RoomType包含由HTML AgilityPack解析的数据,如何按名称(如Pay&Save、Best Available Room Only)对其进行分组
HTML文件位于此处:
谢谢您可以用另一种方法来完成,而不是将3个XPath查询合并,然后尝试按“速率描述”(也称为按元素:
)对它们进行分组
您可以根据“房价描述”来选择LINQ,然后在投影部分,使用相对XPath获取当前“房价描述”下的所有房间类型和房价:
var rooms =
doc.DocumentNode
.SelectNodes("//table[@class='rates']//tr[@class='rate']")
.Select(r => new
{
RateType = r.SelectSingleNode("./td[@class='rate-description']")
.InnerText.CleanInnerText,
RoomTypes = r.SelectNodes("./following-sibling::tr[@class='rooms'][1]//table[@class='rooms']//h2")
.Select(s => new
{
RoomType = s.InnerText.CleanInnerText,
Rate = s.SelectSingleNode(".//parent::td/following-sibling::td[@class='room-price room-price-total'][1]")
.InnerText.CleanInnerText
}).ToArray()
}).ToArray();
请注意上面一些XPath查询开头的句点。这告诉HtmlAgilityPack
查询是相对于当前HtmlNode
的。结果是这样的:
感谢您的代码,这很好,但是,由于预定义程序的结构,我将不得不在稍后的return语句中对它们进行分组,因此,我需要解组数据,但它是以分隔行的形式排列的,但具有相同的RateType和不同的RoomType和Rate。你能给我提个建议吗?Thankst这是一个返回语句,它在上面的代码之后对值进行分组:Thankshow about modify the return statement以便能够在这个答案中使用LINQ,如下所示:?