Home > Mobile >  Can you change a HTML element by ID with C#?
Can you change a HTML element by ID with C#?

Time:08-04

I am currently trying to have a plain HTML file template in folder which I then retrieve from a C# project. I had small placeholder words that I would then replace with the help of a stringbuilder. This would make the HTML template dynamic so I can change certain parts depending on what I need.

But I was wondering if it was possible to find the HTML element by ID or something along those lines. Instead of replacing each place where the placeholder word is, I would instead try to manipulate the HTML element.

I had tried something named HTML Agility Pack but I couldn't seem to get that to work.

I have this file of simple HTML.

<h1 id="test> </h1>

Which I then parse into the HTML Agility Pack and try to find the id of the element and then I try to parse some text into it.

private string DefineHTML(string html, string id)
{
    var doc = new HtmlDocument();
    doc.LoadHtml(html);
    
    doc.GetElementbyId(id).AppendChild(doc.CreateElement("<p>test</p>"));
    
    return doc.Text;
}

But it just outputs the same HTML it got into it instead of adding the next child to the element.

I need it to input the element into the heading element. Like so

<h1 id="test">
    <p>test</p>
</h1>

So I was wondering if there was a way to do this. Since I feel like replacing each placeholder word seems like more trouble than it is worth.

CodePudding user response:

private string DefineHTML(string html, string id)
{
    var doc = new HtmlDocument();
    doc.LoadHtml(html);
    
    var htmlNode = doc.DocumentNode.SelectSingleNode($"//p[@id='{id}']");
    var child = htmlDoc.CreateElement("<p>test</p>");
    htmlNode.AppendChild(child);
    
    return doc.DocumentNode.InnerHtml;
}
  • Related