C# - Extract speciifc div class text using HTMLAgility

c# css html html-agility-pack

Question

I have a code in C# where I want to extract the below value (the text "I want this text" in the HTML code below). I have reformat the HTML code to make it easily readable.

<div class="paste-copy-url" style="margin:0 0 0 0;">
    <h4>My Stats:</h4>
    <div class="line">
        <div class="wrap-input">
            <input onclick="this.select();" value="I want this text" readonly="readonly">
        </div>
    </div>
    <h4>Website Link:</h4>
    <div class="line">
        <div class="wrap-input"><input onclick="this.select();" value="Some value" readonly="readonly">
        </div>
    </div>
</div>

The code I tried (It is giving me the text : "Website Link:"):

var myvaluetoextract = htmlDocument.DocumentNode.SelectSingleNode("//div[@class='paste-copy-url']");

What am I doing wrong? Can I use this approach to get that element (There is only 1 instance of the div class in the page)?

Accepted Answer

var input = htmlDocument.DocumentNode
           .SelectSingleNode("//div[@class='paste-copy-url']//div[@class='wrap-input']/input");
var yourText = input.Attributes["value"].Value;

Popular Answer

You can do it like this:

var myvaluetoextract = htmlDocument.DocumentNode.SelectSingleNode("//div[@class='paste-copy-url']//input");
var value = myvaluetoextract.GetAttributeValue("value", null);

//input means you search for input elements in the div's subtree, recursively. GetAttributeValue is a helper that will never fail, even if the attribute doesn't exists (in this case if will return the 2nd passed parameter - which is null here)




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why