哈,看起来是我编写的库的无耻插件的理想时机!
使用这个库应该很容易实现(顺便说一下,它构建在 HtmlAgility 包之上!):https ://github.com/amoerie/htmlbuilders
(您可以在此处找到 Nuget 包:https://www. nuget.org/packages/HtmlBuilders/)
代码示例:
const string html = "<div class='invoice'><input type='text' name='abc' value='123'/><input id='ohgood' type='text' name='def' value='456'/></div>";
var htmlDocument = new HtmlDocument {OptionCheckSyntax = false}; // avoid exceptions when html is invalid
htmlDocument.Load(new StringReader(html));
var tag = HtmlTag.Parse(htmlDocument); // if there is a root tag
var tags = HtmlTag.ParseAll(htmlDocument); // if there is no root tag
// find looks recursively through the entire DOM tree
var inputFields = tag.Find(t => string.Equals(t.TagName, "input"));
foreach (var inputField in inputFields)
{
Console.WriteLine(inputField["type"]);
Console.WriteLine(inputField["value"]);
if(inputField.HasAttribute("id"))
Console.WriteLine(inputField["id"]);
}
请注意,如果该字段没有指定的属性名称,则 inputField[attribute] 将抛出“KeyNotFoundException”。这是因为 HtmlTag 为其属性实现并重用了 IDictionary 逻辑。
编辑:如果您不在 Web 环境中运行此代码,则需要添加对 System.Web 的引用。这是因为这个库使用了 System.Web 中的 HtmlString 类。只需选择“添加引用”,然后您可以在“程序集 > 框架”下找到它