2013-12-22 156 views
1

HTMLHTML敏捷解析錯誤

<html> 
<head> 
<title>Sample Page</title> 
</head> 
<body> 
<form action="demo_form.asp" id="form1" method="get"> 
    First name: <input type="text" name="fname"><br> 
    Last name: <input type="text" name="lname"><br> 
    <input type="submit" value="Submit"> 
</form> 
</body> 
</html> 

代碼

HtmlDocument doc = new HtmlDocument();  
doc.LoadHtml(File.ReadAllText(@"C:\sample.html")); 
HtmlNode nd = doc.DocumentNode.SelectSingleNode("//form[@id='form1']"); 
//nd.InnerHtml is "". 
//nd.InnerText is "". 

問題

nd.ChildNodes //Collection(to get all nodes in form) is always null. 
nd.SelectNodes("/input") //returns null. 
nd.SelectNodes("./input") //returns null. 
"//form[@id='form1']/input" //returns null. 

我想是一個以訪問形式的標籤的childNodes使用id = form1的一個發生。我在Chrome開發者控制檯中嘗試了相同的xpath,它的工作方式與我想要的完全一樣。 HTMlAgility包在從文件或Web閱讀HTML時遇到問題。

+0

問題是什麼? –

+0

我想要htmlNodecollection中的所有表單標籤的子節點。 –

回答

0

嘗試加載該文件之前添加以下語句:

HtmlNode.ElementsFlags.Remove("form"); 

HtmlAgilityPack的默認行爲將所有表單的內部元素添加爲兄弟而不是子級。上面的語句改變了這種行爲,以便它們(意味着輸入標籤)將顯示爲子節點。

您的代碼應該是這樣的:

HtmlNode.ElementsFlags.Remove("form"); 
HtmlDocument doc = new HtmlDocument();  
doc.LoadHtml(File.ReadAllText(@"C:\sample.html")); 
HtmlNode nd = doc.DocumentNode.SelectSingleNode("//form[@id='form1']"); 
etc... 

引用:

  1. 錯誤問題&修復:http://htmlagilitypack.codeplex.com/workitem/23074
  2. CodePlex網站論壇上發帖:http://htmlagilitypack.codeplex.com/discussions/247206
+1

:D哈哈謝謝你,這工作,我想我已經定期更新我的htmlagility dll –

+0

nuget ftw;) - >是的,它只是從1.4.5版本開始,現在的版本是1.4.6。樂意效勞。 –

1

您的html無效,可能會阻止html敏捷包正常工作。

嘗試從>添加一個DOCTYPE(和XML命名空間)到文檔的開始,改變你的輸入元素的結束標記/>

+0

<!DOCTYPE HTML PUBLIC「 - // W3C // DTD HTML 4.01 Transitional // EN」「http://www.w3.org/TR/html4/loose.dtd」> 示例頁面 <形式行動= 「demo_form.asp」 ID = 「form1的」 方法= 「GET」 > 名字:
姓氏:
' 已驗證通過http://validator.w3.org/check:通過。但得到同樣的錯誤。 :( –