2013-03-23 51 views

回答

0

好了,先把文檔根擁有所有內容

//create a new document 
var _htmlDoc = new HtmlAgilityPack.HtmlDocument(); 

//fill it with html 
_htmlDoc.Load(filePath) or _htmlDoc.LoadHtml(string...) 

//get the document root node - it has all the contents 
var docuemntNode = _htmlDoc.DocumentNode; 

然後...使用LINQ或XPath查詢的節點

string xpathExpressionSting = "//p"; 
var contents = htmlDoc.DocumentNode.SelectNodes(xpathExpressionSting) 
//this would get paragraph tag nodes 
+0

任何人都知道如何遞歸遍歷下來HTML文檔對象模型,尋找文本節點?我嘗試保存.txt文件中頁面上沒有標籤的所有文本。但是,而不是500行,我得到重複6000行。我做錯了什麼? TextWriter tw = new StreamWriter(「html.txt」); foreach(HtmlNode文本在soup.DocumentNode.Descendants()) { string subText = text.InnerText; resultText + = subText; tw.WriteLine(resultText); } tw.Close(); – 2013-03-25 14:20:26

+0

它看起來像內部文本也可能包含封閉的節點。我不確定。請問作爲一個新的問題 – user1778606 2013-03-26 01:15:09

+0

不知道如何做遞歸,雖然我認爲你可以通過 - var nodes = doc.DocumentNode.SelectNodes(「// text()」)來選擇它們 - 儘管我並不完全確定xpath語法 – user1778606 2013-03-26 01:20:24