Home > Blockchain >  Html Agility Pack - Remove element by id
Html Agility Pack - Remove element by id

Time:11-09

I'm trying remove specific piece of code by element id with help of Html Agility Pack. Html:

<div id="id00">
    <h1>Title</h1>
</div>
<div id="id10">
    <div id="id11">
        <h2>Title 2</h2>        
        <p>Some text</p>
    </div>
    <a id="idToRemove" href="#">Anchor text</a>
</div>

My method:

public static string RemoveElement(string html, string elementId)
{
    elementId = "idToRemove"; 
    HtmlDocument htmlDoc = new HtmlDocument();
    htmlDoc.LoadHtml(html);
    var node = htmlDoc.GetElementbyId(elementId);
    node.Remove();
    html = htmlDoc.Text;
    return html;
}

Unfortunately it's not working at all.

CodePudding user response:

It works, but htmlDoc.Text is the wrong property, use:

return htmlDoc.DocumentNode.OuterHtml;
  • Related