C#: find HTML attribute and replace value using HTMLAgilityPack

dom html html-agility-pack

Question

Hi I am experimenting how to use HTMLAgilityPack Vs using Regex (Not sure which is more Expensive). My question id with HTMLAgilityPack I am able to extract the required attribute and replace it with a new one; however, I cant seems to update the original text. Here is the code;

string input = @"<area shape=""rect"" coords=""0,0,82,126"" href=""one"" alt=""Sun""> <area shape=""rect"" coords=""0,0,82,126"" href=""two"" alt=""Sun"" > <area shape=""rect"" coords=""0,0,82,126"" href=""Three"" alt=""Sun"" >";

HtmlDocument document = new HtmlDocument();
document.LoadHtml(input);

HtmlNodeCollection nodes = document.DocumentNode.SelectNodes("//area");

for (int i = 0; i < nodes.Count; i++ )
{
    HtmlNode node = nodes[i];
    var href = node.Attributes["href"].Value;
    //Reassigning href value
    node.Attributes["href"].Value="Re-Assign ["+i+"]";
}

Now I want to make this reflect in the original "input" variable. Any idea how to proceed?

Thanks

Popular Answer

I am also experimenting with how to use the Agility Pack. Try with:

String HTML = nodes.DocumentNode.WriteTo();

you need to write the updates in the original text.




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