2013-03-23 68 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