如何使用 HTML Agility Pack 将输入标签添加到表单?

How do I add an input tag to a form using HTML Agility Pack?

我从一组表格开始:

<form action="/Test/1">
    <p>This is my 1st form.</p>
    <button type="submit">Submit Form</button>
</form>

<form action="/Test/2">
    <div>This is my 2nd form.</div>
    <input type="submit" value="Submit Form" />
    <input type="hidden" name="var1" value="123" />
</form>

并且我尝试向页面上的所有表单添加输入标签:

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(inputHtml); // inputHtml is a string containing the forms above
var nodes = doc.DocumentNode.SelectNodes("//form");
if (nodes != null)
{
    foreach (var node in nodes)
    {
        node.AppendChild(HtmlNode.CreateNode("<input type=\"hidden\" name=\"var2\" value=\"456\" />"));
    }
}
var model = doc.DocumentNode.OuterHtml;

这就是我所期待的:

<form action="/Test/1">
    <p>This is my 1st form.</p>
    <button type="submit">Submit Form</button>
    <input type="hidden" name="var2" value="456">
</form>

<form action="/Test/2">
    <div>This is my 2nd form.</div>
    <input type="submit" value="Submit Form">
    <input type="hidden" name="var1" value="123">
    <input type="hidden" name="var2" value="456">
</form>

然而,这就是我得到的结果:(为便于阅读而添加的换行符和间距)

<form action="/Test/1">
    <input type="hidden" name="var2" value="456">
</form>
    <p>This is my 1st form.</p>
    <button type="submit">Submit Form</button>
</form>

<form action="/Test/2">
    <input type="hidden" name="var2" value="456">
</form>
    <div>This is my 2nd form.</div>
    <input type="submit" value="Submit Form">
    <input type="hidden" name="var1" value="123">
</form>

现在我有重复的 </form> 结束标签。

使用 HTML Agility Pack 获得预期结果的正确方法是什么?

更新: 预期结果中的第二个表单有一个错误,显示重复的表单标签。 (复制粘贴错误)

只需在加载文档之前调用 HtmlAgilityPack.HtmlNode.ElementsFlags.Remove("form");,加载后应该会按预期工作。

在侧节点上:

既然可以这样写,为什么还要跳过双引号呢:

"<input type='hidden' name='var2' value='456'/>"