1

私は 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>

私がやりたいことは、Test Row Twoに関連付けられた Test Content を取得することです。隣接するセルのレポートの名前を調べる必要があります。

4

1 に答える 1

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 );

        }
    }
}
于 2012-09-12T18:09:42.707 に答える