用HTML敏捷包解析表格
问题描述:
我想从表单中提取所有输入元素。当我解析以下形式:用HTML敏捷包解析表格
<form>
<input name='test1' type='text'>
<input name='test2' type='text'>
<input name='test3' type='text'>
</form>
一切都工作正常,HTML敏捷性包能够检测在表单中输入元素,但如果它有类似下面的DIV父节点,它不会被检测到。
<form>
<div><input name='test1' type='text'></div>
<div><input name='test2' type='text'></div>
<div><input name='test3' type='text'></div>
</form>
我用下面的代码
HtmlNode.ElementsFlags.Remove("form");
foreach (HtmlAgilityPack.HtmlNode node in postForm.Elements("input"))
{
HtmlAgilityPack.HtmlAttribute valueAttribute = node.Attributes["value"];
}
谁能告诉我哪里出了问题?谢谢
答
HtmlNode.Elements
方法被匹配匹配名第一代子节点。将输入放入<div>
标记后,它们将成为表单元素的第二代子节点。
为了让你的代码工作中使用HtmlNode.Descendants
方法,获得具有匹配名称的所有后代节点:
foreach (HtmlAgilityPack.HtmlNode node in postForm.Descendants("input"))
{
HtmlAgilityPack.HtmlAttribute valueAttribute = node.Attributes["value"];
}
答
我不记得“.Elements()
”是做什么的,但我认为它只是返回子节点......在你的情况下,你的表单的直接孩子是divs
。
您可以使用XPath有一点更多的控制:
.SelectNodes("//form/div/input")
这将在形式返回输入节点列表,明知输入withing div标签。
在这里您可以看到带有示例的XPATH TUTORIAL。
答
使用Descendants()
而不是Elements()
- 后来只适用于直接孩子,但你输入元素嵌套的div内:
foreach (HtmlAgilityPack.HtmlNode node in postForm.Descendants("input"))
{
HtmlAgilityPack.HtmlAttribute valueAttribute = node.Attributes["value"];
}
什么是这里postForm – Kurkula 2016-12-27 03:33:05