我从一组表格开始:
<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实现所需结果的正确方法是什么?
更新:预期结果中的第二个表单中有一个错误,显示重复的表单标记。 (复制粘贴错误)
答案 0 :(得分:3)
只需在加载文档之前调用HtmlAgilityPack.HtmlNode.ElementsFlags.Remove("form");
,之后该附加应该按预期工作。
:
为什么打扰跳过双引号,当你可以把它写成:
"<input type='hidden' name='var2' value='456'/>"