2012-03-27 99 views
0

我想從表單中提取所有輸入元素。當我解析以下形式:用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"]; 
} 

誰能告訴我哪裏出了問題?謝謝

+0

什麼是這裏postForm – Kurkula 2016-12-27 03:33:05

回答

6

HtmlNode.Elements方法被匹配匹配名第一代子節點。將輸入放入<div>標記後,它們將成爲表單元素的第二代子節點。

爲了讓你的代碼工作中使用HtmlNode.Descendants方法,獲得具有匹配名稱的所有後代節點:

foreach (HtmlAgilityPack.HtmlNode node in postForm.Descendants("input")) 
{ 
    HtmlAgilityPack.HtmlAttribute valueAttribute = node.Attributes["value"]; 
} 
2

我不記得「.Elements()」是做什麼的,但我認爲它只是返回子節點......在你的情況下,你的表單的直接孩子是divs

您可以使用XPath有一點更多的控制:

.SelectNodes("//form/div/input") 

這將在形式返回輸入節點列表,明知輸入withing div標籤。

在這裏您可以看到帶有示例的XPATH TUTORIAL

2

使用Descendants()而不是Elements() - 後來只適用於直接孩子,但你輸入元素嵌套的div內:

foreach (HtmlAgilityPack.HtmlNode node in postForm.Descendants("input")) 
{ 
    HtmlAgilityPack.HtmlAttribute valueAttribute = node.Attributes["value"]; 
}