如何使用 HtmlAgilityPack 获取表单中的所有输入元素而不会出现空引用错误 [英] How to get all input elements in a form with HtmlAgilityPack without getting a null reference error

查看:18
本文介绍了如何使用 HtmlAgilityPack 获取表单中的所有输入元素而不会出现空引用错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例 HTML:

 <html><body>
     <form id="form1">
       <input name="foo1" value="bar1" />
       <!-- Other elements -->
     </form>
     <form id="form2">
       <input name="foo2" value="bar2" />
       <!-- Other elements -->
     </form>   
 </body></html>

测试代码:

HtmlDocument doc = new HtmlDocument();
doc.Load(@"D:	est.html");
foreach (HtmlNode node in doc.GetElementbyId("form2").SelectNodes(".//input"))
{
    Console.WriteLine(node.Attributes["value"].Value);            
}

语句 doc.GetElementbyId("form2").SelectNodes(".//input") 给了我一个空引用.

The statement doc.GetElementbyId("form2").SelectNodes(".//input") gives me a null reference.

我做错了什么吗?谢谢.

Anything I did wrong? thanks.

推荐答案

您可以执行以下操作:

HtmlNode.ElementsFlags.Remove("form");

HtmlDocument doc = new HtmlDocument();

doc.Load(@"D:	est.html");

HtmlNode secondForm = doc.GetElementbyId("form2");

foreach (HtmlNode node in secondForm.Elements("input"))
{
    HtmlAttribute valueAttribute = node.Attributes["value"];

    if (valueAttribute != null)
    {
        Console.WriteLine(valueAttribute.Value);
    }
}

默认情况下,HTML Agility Pack 将表单解析为空节点,因为它们可以与其他 HTML 元素重叠.第一行 (HtmlNode.ElementsFlags.Remove("form");) 禁用此行为,允许您在第二个表单中获取输入元素.

By default HTML Agility Pack parses forms as empty node because they are allowed to overlap other HTML elements. The first line, (HtmlNode.ElementsFlags.Remove("form");) disables this behavior allowing you to get the input elements inside the second form.

更新:表单元素重叠示例:

<table>
<form>
<!-- Other elements -->
</table>
</form>

元素在表格内部开始,但在表格元素外部关闭.这在 HTML 规范中是允许的,并且 HTML Agility Pack 必须处理它.

The element begins inside a table but is closed outside the table element. This is allowed in the HTML specification and HTML Agility Pack has to deal with it.

这篇关于如何使用 HtmlAgilityPack 获取表单中的所有输入元素而不会出现空引用错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆