C# - Get the text inside tags using HTML Agility Pack

无人久伴 提交于 2019-12-12 17:01:46

问题


I have used the following code to parse HTML document & store it as CSV file.

string actuald=null;
string data1 = File.ReadAllText("E://text.html");
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(data1);
HtmlNodeCollection col = doc.DocumentNode.SelectNodes("//pre");

foreach (HtmlNode node in col)
{
     actuald=node.Attributes[""].Value;
}
File.WriteAllText("E://text.csv",actuald);
Console.WriteLine("Data Converted");
Console.ReadKey();

in the html document, the content i need to extract lies between < pre > < /pre > . the content of my file looks like

<HTML><HEAD><TITLE>NCEDC_Search_Results</TITLE></HEAD><BODY>Your search parameters are:<ul>
<li>start_time=1973/01/01,00:00:00
<li>end_time=2037/01/01,00:00:00
<li>minimum_magnitude=3.0
<li>maximum_magnitude=10
<li>etype=E
<li>rflag=A,F,H,I
<li>system=selected
<li>format=ncread
</ul>
<PRE>
Date       Time             Lat       Lon  Depth   Mag Magt  Nst Gap  Clo  RMS  SRC   Event ID
----------------------------------------------------------------------------------------------
1973/01/01 06:59:19.23  36.8037 -121.5087   5.65  3.60   Md   28  35    6 0.09 NCSN    1013957 
1973/01/01 07:57:39.65  37.0925 -121.5055   9.19  3.10   ML   45  90    5 0.07 NCSN    1013959 
</pre></html>

but in the html doc I have no class specified under any of the html tags? What content should I give in the attributes[""]?


回答1:


To get text inside a node:

actuald = node.InnerText;

To get text including the HTML tags

actuald = node.InnerHtml;


来源:https://stackoverflow.com/questions/17611592/c-sharp-get-the-text-inside-tags-using-html-agility-pack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!