문제

C#에서 데이터를 그룹화하고 html 파일을 구문 분석하여 모든 데이터를 얻었습니다. 이제 다음과 같이 그룹화하려고 합니다.

enter image description here

선택된 라인은 상위 라인이고 다음 하위 라인을 포함합니다. 제가 작업 중인 코드는 다음과 같습니다.

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 파일은 여기에 있습니다: http://notepad.cc/share/g0zh0TcyaG

감사합니다

도움이 되었습니까?

해결책

3개의 XPath 쿼리를 통합하는 대신 "Rate Description"(또는 요소별:)별로 그룹화하려고 합니다. <td class="rate-description">), 다른 방법으로 할 수 있습니다.

"요금 설명"을 기준으로 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.결과는 대략 이렇습니다.

enter image description here

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top