Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

c# - Parsing HTML with CSQuery

How can I retrieve the value from a div tag via the ID using CSQuery?

For example,

<h3>
    <div id='type'>
        Room 1
    </div>
    <div id='price'>
        145
    </div>
</h3>

In this case I'd like to get the content inside type and price.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ok, here is how you do this with a full working example.

Html

This includes your invalid/duplicate id html which you have no control over

var html = @"<h3>
            <div id='lib_presta'>
                Chambre standard 1 pers du <span class=''>03/03/2014</span>  au <span class=''>05/03/2014 </span>
            </div>
            <div id='prix_presta'>
                127.76 &euro;
            </div>
        </h3><h3>
            <div id='lib_presta'>
                Chambre standard 2 pers du <span class=''>03/03/2014</span>  au <span class=''>05/03/2014 </span>
            </div>
            <div id='prix_presta'>
                227.76 &euro;
            </div>
        </h3>";

C# Code

This loads the dom elements by their id's into two lists of descriptions and prices. It then projects them into a list of HotelAvailability objects using the key values of both collections as the HotelName and Price properties.

        CQ dom = html;

        var libs = dom["#lib_presta"];
        var prixs = dom["#prix_presta"];

        var list = libs.Zip(prixs, (k, v) => new { k, v })
          .Select(h => new HotelAvailablity { HotelName = h.k.InnerText.Trim(), Price = h.v.InnerText.Trim() });

Screen grab

Run the above in a console app to test it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...