[英]How do I add an input tag to a form using HTML Agility Pack?
I start off with a set of forms: 我从一组表格开始:
<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>
And I attempt to add an input tag to all forms on the page: 我尝试在页面上的所有表单中添加一个输入标记:
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;
This is what I was expecting: 这就是我所期待的:
<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>
However, this is what I get as a result: (line breaks and spacing added for readability) 但是,这就是我得到的结果:( 添加了换行符和间距以提高可读性)
<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>
Now I have duplicate </form>
closing tags. 现在我有重复的</form>
结束标记。
What is the proper way to achieve the desired result using HTML Agility Pack? 使用HTML Agility Pack实现所需结果的正确方法是什么?
Update: 2nd form in expected results had a bug in it showing the duplicate form tag. 更新:预期结果中的第二个表单中有一个错误,显示重复的表单标记。 (Copy-paste error) (复制粘贴错误)
Just call HtmlAgilityPack.HtmlNode.ElementsFlags.Remove("form");
只需调用HtmlAgilityPack.HtmlNode.ElementsFlags.Remove("form");
before you load your document, after that append should work as you expect. 在加载文档之前,该附加应该按预期工作。
on a side node: 在一个侧节点上:
why bother skipping double quotes when you can write it as: 为什么打扰跳过双引号,当你可以写为:
"<input type='hidden' name='var2' value='456'/>"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.