如何在c#中解析HTMLDocument?
我想使用c#中的一个简单应用程序获取html页面的文本? 如果有嵌套元素 即如何在c#中解析HTMLDocument?,c#,asp.net,html-agility-pack,C#,Asp.net,Html Agility Pack,我想使用c#中的一个简单应用程序获取html页面的文本? 如果有嵌套元素 即 从这个htmlSnippet我怎样才能得到值?我不确定,你需要什么。。。根据您的示例,是否需要字符串“**ABC****1****XYZ****2**” 那么这应该是可行的:htmlSnippet.Body.OuterText 编辑:好的,尝试一个单独值的示例 HtmlElement tableElement = FindElement(HtmlDocument.Body, "table"); foreach(Html
从这个
htmlSnippet
我怎样才能得到值?我不确定,你需要什么。。。根据您的示例,是否需要字符串“**ABC****1****XYZ****2**”
那么这应该是可行的:htmlSnippet.Body.OuterText
编辑:好的,尝试一个单独值的示例
HtmlElement tableElement = FindElement(HtmlDocument.Body, "table");
foreach(HtmlElement row in tableElement.Children)
{
if (row.Name.ToLower() == "tr")
{
// create whatever class you use for a row
foreach(HtmlElement cell in row.Children)
{
if (cell.Name.ToLower() == "td")
{
// add a new cell to your row using cell.InnerText
}
}
}
}
// *** snip ***
private HtmlElement FindElement(HtmlElement element, string name)
{
if (element.Name.ToLower() == name)
{
return element;
}
foreach(HtmlElement child in element.Children)
{
HtmlElement test = FindElement(test, name);
if (test != null)
{
return test;
}
}
return null;
}
抱歉,我现在没有Visual Studio来测试代码。。。祝你好运;-) 我的示例包含两行。每行包含两列。我想要每个列的值。我想将它们保存为数据库中的行。啊,好的,然后,您必须遍历htmlSnippet.Body.Children并搜索具有正确名称的htmlSnippet.Body.Children。如果我编写htmlSnippet.DocumentNode.Children,则htmlSnippet.Body.Children不起作用。如何搜索htmlement请发送一些语法谢谢回复。如何使用上述语法。在项目上编写“向我显示错误消息”。添加参考。如何保存此文件
HtmlDocument htmlSnippet = new HtmlDocument();
htmlSnippet = LoadHtmlSnippetFromFile();
private HtmlDocument LoadHtmlSnippetFromFile()
{
//TextReader reader = File.OpenText(Server.MapPath("~/App_Data/HtmlSnippet.txt"));
WebClient webClient = new WebClient();
const string strUrl = "http://www.dsebd.org/latest_PE_all2_08.php";
Stream reader = webClient.OpenRead(strUrl);
HtmlDocument doc = new HtmlDocument();
doc.Load(reader);
reader.Close();
return doc;
}
HtmlElement tableElement = FindElement(HtmlDocument.Body, "table");
foreach(HtmlElement row in tableElement.Children)
{
if (row.Name.ToLower() == "tr")
{
// create whatever class you use for a row
foreach(HtmlElement cell in row.Children)
{
if (cell.Name.ToLower() == "td")
{
// add a new cell to your row using cell.InnerText
}
}
}
}
// *** snip ***
private HtmlElement FindElement(HtmlElement element, string name)
{
if (element.Name.ToLower() == name)
{
return element;
}
foreach(HtmlElement child in element.Children)
{
HtmlElement test = FindElement(test, name);
if (test != null)
{
return test;
}
}
return null;
}