我关注了html代码:
<tr>
<td headers="header1"><b><a href="www.site.com">TITLE </a></b></td>
<td headers="header2"></td>
<td headers="header3" class="centrato">23/04/2014</td>
</tr>
我需要存储在数据表中:
HREF VALUE in "Link" column;
TITLE in "Title" column;
23/04/2014 in "Date" column;
我试过了:
int i = 0;
foreach (HtmlNode node in tmlDoc.DocumentNode.SelectNodes("//td[@headers='header1']"))
{
table.Rows.Add();
table.Rows[i]["Post"] = node.InnerText;
i++;
}
此代码允许我在数据表中添加所有标题但我无法添加DATE和HREF,您能帮我吗?
答案 0 :(得分:2)
你可以这样做:
//select all `<tr>` that contains specific `<td>`
foreach (HtmlNode node in tmlDoc.DocumentNode.SelectNodes("//tr[td[@headers='header1']]"))
{
table.Rows.Add();
//get <td headers='header1'> in current <tr>
var header1 = node.SelectSingleNode("./td[@headers='header1']");
table.Rows[i]["Title"] = header1.InnerText;
//get <a> in header1 then get it's href attribute value
table.Rows[i]["Link"] = header1.SelectSingleNode(".//a").GetAttributeValue("href", "");
//get innerText of <td headers='header1'> in current <tr>
table.Rows[i]["Post"] = node.SelectSingleNode("./td[@headers='header3']").InnerText;
i++;
}
答案 1 :(得分:0)
InnerText 只是为您提供标记之间的文字。要访问Href
或Id
或......您应该使用GetAttributeValue
方法。
int i = 0;
foreach (HtmlNode node in tmlDoc.DocumentNode.SelectNodes("//tr"))
{
table.Rows.Add();
table.Rows[i]["Link"] = node.SelectSingleNode("//a").GetAttributeValue("href", "");
table.Rows[i]["Title"] = node.SelectSingleNode("//a").InnerText;
table.Rows[i]["Date"] = node.SelectSingleNode("//td[@headers='header3']").InnerText;
i++;
}