我正在开发一个C#控制台应用程序。最终目标是在表中查找特定行,然后单击链接以下载由旧Web应用程序生成的文件。 (这已经很老了,所以我没有API供我使用)
该表遵循以下结构:
<html>
<head>
<title>Test Table Page</title>
</head>
<body>
<table border="1" cellpadding="3" cellspacing="5">
<tr>
<td>Test Row One</td>
<td>Test Content</td>
</tr>
<tr>
<td>Test Row Two</td>
<td>Test Content</td>
</tr>
<tr>
<td>Test Row Three</td>
<td>Test Content</td>
</tr>
</table>
</body>
我想要做的是获取与测试第二行相关联的测试内容。我需要在相邻单元格中找到报告的名称。
答案 0 :(得分:1)
如果您认为HTML将符合XML,您可以使用下面的XML解析器(使用XPath)。 就个人而言,我喜欢避免使用HTML解析器,因为它们非常复杂。就像用电锯将树枝折成两半一样。有时,没有别的办法,但如果有一个更简单的解决方案,那么首先尝试。
相关代码段
var l_contentCell = l_navigator.SelectSingleNode( "//td[preceding-sibling::td/text()='Test Row Two']" );
完整源代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
namespace XmlSandbox {
class Program {
static void Main( string[] args ) {
string l_xmlLiteral =
"<html>\n" +
" <head>\n" +
" <title>Test Table Page</title>\n" +
" </head>\n" +
" <body>\n" +
" <table border=\"1\" cellpadding=\"3\" cellspacing=\"5\">\n" +
" <tr>\n" +
" <td>Test Row One</td>\n" +
" <td>Test Content</td>\n" +
" </tr>\n" +
" <tr>\n" +
" <td>Test Row Two</td>\n" +
" <td>Test Content</td>\n" +
" </tr>\n" +
" <tr>\n" +
" <td>Test Row Three</td>\n" +
" <td>Test Content</td>\n" +
" </tr>\n" +
" </table>\n" +
" </body>\n" +
"</html>";
var l_document = XDocument.Parse( l_xmlLiteral );
var l_navigator = l_document.CreateNavigator();
var l_contentCell = l_navigator.SelectSingleNode( "//td[preceding-sibling::td/text()='Test Row Two']" );
Console.WriteLine( l_contentCell.Value );
}
}
}