C# - Extract speciifc div class text using HTMLAgility

c# css html html-agility-pack


I want to extract the value below from some C# code (the text "I want this text" in the HTML code below). To make the HTML code more legible, I reorganized it.

<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">

I tried the following code, which displays the text "Website Link:"

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

Why am I misusing this? Can I use this method to get that element (the div class only appears once on 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 may accomplish it as follows:

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

//input signifies that you look forinput components in thediv in a recursive manner.GetAttributeValue is a helper that, even if the attribute doesn't exist, will always succeed; in this instance, it will return the second passed argument, which isnull 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