user778930
user778930

Reputation: 87

C#: find HTML attribute and replace value using HTMLAgilityPack

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

Upvotes: 0

Views: 3458

Answers (2)

rajwill
rajwill

Reputation: 21

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.

Upvotes: 2

Anirudha
Anirudha

Reputation: 32827

You were missing doc.Save(yourFileName);

Upvotes: 0

Related Questions