我刚刚写了这个测试,看看我是不是疯了......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
namespace HtmlAgilityPackFormBug
{
class Program
{
static void Main(string[] args)
{
var doc = new HtmlDocument();
doc.LoadHtml(@"
<!DOCTYPE html>
<html>
<head>
<title>Form Test</title>
</head>
<body>
<form>
<input type=""text"" />
<input type=""reset"" />
<input type=""submit"" />
</form>
</body>
</html>
");
var body = doc.DocumentNode.SelectSingleNode("//body");
foreach (var node in body.ChildNodes.Where(n => n.NodeType == HtmlNodeType.Element))
Console.WriteLine(node.XPath);
Console.ReadLine();
}
}
}
它输出:
/html[1]/body[1]/form[1]
/html[1]/body[1]/input[1]
/html[1]/body[1]/input[2]
/html[1]/body[1]/input[3]
但是,如果我改变 <form>
至 <xxx>
它给了我:
/html[1]/body[1]/xxx[1]
(应该如此)。所以...看起来这些输入元素不包含在表单中,而是直接包含在正文中,就好像 <form>
只是立即关闭自己。那是怎么回事?这是错误吗?
通过源代码挖掘,我看到:
ElementsFlags.Add("form", HtmlElementFlag.CanOverlap | HtmlElementFlag.Empty);
它有“空”标志,像 META 和 IMG。为什么??表单绝对不应该是空的。
最佳答案
this workitem 中也报告了这一点.它包含 DarthObiwan 建议的解决方法。
You can change this without recompiling. The ElementFlags list is a static property on the HtmlNode class. It can be removed with
HtmlNode.ElementsFlags.Remove("form");
before doing the document load
关于c# - HtmlAgilityPack -- <form> 是否由于某种原因自行关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4218847/