使用HtmlAgilityPack在body标签周围添加表单标签

时间:2013-03-25 10:24:53

标签: c# html html-agility-pack

如何在HMLDocument周围添加表单标记?

对于给定的HTML

<html>
 <head>
  <title></title>
 </head>
 <body>
  <p>Full name: <input name="FullName" type="text" value=""></p> 
  <p><input name="btnSubmit" type="submit" value="Submit"></p>
 </body>
</html>

以及以下代码......

var doc = new HtmlDocument();
doc.OptionAutoCloseOnEnd = true;
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);
}
return doc.DocumentNode.OuterHtml;

我收回以下内容,请注意我们在结束</form>代码上方没有结束</body>标记

<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>
 </body>
</html>

1 个答案:

答案 0 :(得分:2)

FORM元素有特殊处理。有关详情,请参阅此处:HtmlAgilityPack -- Does <form> close itself for some reason?

所以,你可以这样做:

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);
}

但它会告诉你:

<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>

这是合乎逻辑的,你不会以新的形式包围任何东西。所以,你可以这样做:

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);
}

这会得到你:

<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>

这不是唯一的方法,但它有效,并且您不一定要删除FORM特殊处理。