Selecting attribute values with html Agility Pack

23,507

Solution 1

Html Agility Pack does not support attribute selection.

Solution 2

You can directly grab the attribute if you use the HtmlNavigator instead.

//Load document from some html string
HtmlDocument hdoc = new HtmlDocument();
hdoc.LoadHtml(htmlContent);

//Load navigator for current document
HtmlNodeNavigator navigator = (HtmlNodeNavigator)hdoc.CreateNavigator();

//Get value from given xpath
string xpath = "//div[@id='topslot']/a/img/@src";
string val = navigator.SelectSingleNode(xpath).Value;

Solution 3

You may use the method "GetAttributeValue".

Example:

//[...] code before needs to load a html document
HtmlAgilityPack.HtmlDocument htmldoc = e.Document;
//get all nodes "a" matching the XPath expression
HtmlNodeCollection AllNodes = htmldoc.DocumentNode.SelectNodes("*[@class='item']/p/a");
//show a messagebox for each node found that shows the content of attribute "href"
foreach (var MensaNode in AllNodes)
{
     string url = MensaNode.GetAttributeValue("href", "not found");
     MessageBox.Show(url);
}

Solution 4

Html Agility Pack will support it soon.

http://htmlagilitypack.codeplex.com/Thread/View.aspx?ThreadId=204342

Solution 5

Reading and Writing Attributes with Html Agility Pack

You can both read and set the attributes in HtmlAgilityPack. This example selects the < html> tag and selects the 'lang' (language) attribute if it exists and then reads and writes to the 'lang' attribute.

In the example below, the doc.LoadHtml(this.All), "this.All" is a string representation of a html document.

Read and write:

            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(this.All);
            string language = string.Empty;
            var nodes = doc.DocumentNode.SelectNodes("//html");
            for (int i = 0; i < nodes.Count; i++)
            {
                if (nodes[i] != null && nodes[i].Attributes.Count > 0 && nodes[i].Attributes.Contains("lang"))
                {
                    language = nodes[i].Attributes["lang"].Value; //Get attribute
                    nodes[i].Attributes["lang"].Value = "en-US"; //Set attribute
                }
            }

Read only:

            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(this.All);
            string language = string.Empty;
            var nodes = doc.DocumentNode.SelectNodes("//html");
            foreach (HtmlNode a in nodes)
            {
                if (a != null && a.Attributes.Count > 0 && a.Attributes.Contains("lang"))
                {
                    language = a.Attributes["lang"].Value;
                }
            }
Share:
23,507
Vegar
Author by

Vegar

SOreadytohelp

Updated on September 02, 2021

Comments

  • Vegar
    Vegar over 2 years

    I'm trying to retrieve a specific image from a html document, using html agility pack and this xpath:

    //div[@id='topslot']/a/img/@src
    

    As far as I can see, it finds the src-attribute, but it returns the img-tag. Why is that?

    I would expect the InnerHtml/InnerText or something to be set, but both are empty strings. OuterHtml is set to the complete img-tag.

    Are there any documentation for Html Agility Pack?

  • clamchoda
    clamchoda over 10 years
    I just used it to select all divs where attribute align is set to center. "//div[@align='center']"
  • Pierluc SS
    Pierluc SS over 9 years
    It is possible with a little workaround, please see my answer below.
  • Andre
    Andre over 8 years
    While this works for reading the attribute's value it is not possible to modify it. Calling .SetValue("new_value") on the selected attribute node throws a System.NotSupportedException since the returned HtmlNodeNavigator is read-only.
  • David S.
    David S. over 7 years
    Isn't this answer a direct contradiction to the accepted answer (modification was not part of the question)?
  • Pierluc SS
    Pierluc SS over 7 years
    @DavidS. I guess the OP just never bothered switching it since I added this answer roughly 4 years later
  • ygoe
    ygoe over 5 years
    Here's the updated link: web.archive.org/web/20110109221024/http://… And it doesn't seem to have turned into a release.