Add form tag around a body tag using HtmlAgilityPack
See the question and my original answer on StackOverflowThe FORM element has a special treatment. See here on SO for more: HtmlAgilityPack -- Does <form> close itself for some reason?
So, you could do this:
var doc = new HtmlDocument();
HtmlNode.ElementsFlags.Remove("form"); // remove special handling for FORM
doc.LoadHtml(input);
var body = doc.DocumentNode.SelectSingleNode("//body");
if (doc.DocumentNode.SelectNodes("//form[@action]") == null)
{
var form = doc.CreateElement("form");
form.Attributes.Add("action", "/pages/event/10302");
body.PrependChild(form);
}
but it will get you this:
<html>
<head>
<title></title>
</head>
<body>
<form action="/pages/event/10302"></form>
<p>Full name: <input name="FullName" type="text" value=""></p>
<p><input name="btnSubmit" type="submit" value="Submit"></p>
</body>
</html>
Which is logical, you don't surround anything in that new form. So, instead you can do this:
var doc = new HtmlDocument();
doc.LoadHtml(input);
var body = doc.DocumentNode.SelectSingleNode("//body");
if (doc.DocumentNode.SelectNodes("//form[@action]") == null)
{
var form = body.CloneNode("form", true);
form.Attributes.Add("action", "/pages/event/10302");
body.ChildNodes.Clear();
body.PrependChild(form);
}
which will get you this:
<html>
<head>
<title></title>
</head>
<body><form action="/pages/event/10302">
<p>Full name: <input name="FullName" type="text" value=""></p>
<p><input name="btnSubmit" type="submit" value="Submit"></p>
</form></body>
</html>
This is not the only way, but it works, and you don't necessarily have to remove the FORM special treatment.