C# - Extract speciifc div class text using HTMLAgility

c# css html html-agility-pack


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">
    <h4>Website Link:</h4>
    <div class="line">
        <div class="wrap-input"><input onclick="this.select();" value="Some value" readonly="readonly">

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

10/7/2013 9:32:12 AM

Accepted Answer

var input = htmlDocument.DocumentNode
var yourText = input.Attributes["value"].Value;
10/7/2013 9:47:12 AM

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)

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow