So I have an HTML snippet that I want to modify using C#.
<div>
This is a specialSearchWord that I want to link to
<img src="anImage.jpg" />
<a href="foo.htm">A hyperlink</a>
Some more text and that specialSearchWord again.
</div>
and I want to transform it to this:
<div>
This is a <a class="special" href="http://mysite.com/search/specialSearchWord">specialSearchWord</a> that I want to link to
<img src="anImage.jpg" />
<a href="foo.htm">A hyperlink</a>
Some more text and that <a class="special" href="http://mysite.com/search/specialSearchWord">specialSearchWord</a> again.
</div>
I’m going to use HTML Agility Pack based on the many recommendations here, but I don’t know where I’m going. In particular,
- How do I load a partial snippet as a string, instead of a full HTML document?
- How do edit?
- How do I then return the text string of the edited object?
InnerHtmlproperty directly (orTexton text nodes) or modifying the dom tree by using e.g.AppendChild,PrependChildetc.HtmlDocument.DocumentNode.OuterHtmlproperty or useHtmlDocument.Savemethod (personally I prefer the second option).As to parsing, I select the text nodes which contain the search term inside your
div, and then just usestring.Replacemethod to replace it:And saving the result to a string: