touyets
touyets

Reputation: 1325

C# - Extract speciifc div class text using HTMLAgility

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)?

Upvotes: 0

Views: 1370

Answers (2)

Simon Mourier
Simon Mourier

Reputation: 139187

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)

Upvotes: 0

L.B
L.B

Reputation: 116178

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

Upvotes: 4

Related Questions