1

次の HTML では、table要素を解析できますが、要素をスキップする方法がわかりませんth

td要素だけを取得したいのですが、使用しようとすると:

foreach (HtmlNode cell in row.SelectNodes("td"))

...例外が発生します。

<table class="tab03">
  <tbody>
    <tr>
      <th class="right" rowspan="2">first</th>
    </tr>
    <tr>
      <th class="right">lp</th>
      <th class="right">name</th>
    </tr>
    <tr>
      <td class="right">1</td>
      <td class="left">house</td>
    </tr>
    <tr>
      <th class="right" rowspan="2">Second</th>
    </tr>
    <tr>
      <td class="right">2</td>
      <td class="left">door</td>
    </tr>
  </tbody>
</table>

私のコード:

var document = doc.DocumentNode.SelectNodes("//table");
string store = "";

if (document != null)
{
    foreach (HtmlNode table in document)
    {
        if (table != null)
        {
            foreach (HtmlNode row in table.SelectNodes("tr"))
            {
                store = "";
                foreach (HtmlNode cell in row.SelectNodes("th|td"))
                {
                    store = store + cell.InnerText+"|";
                }

                sw.Write(store );
                sw.WriteLine();  
            }
        }
    }
}

sw.Flush();
sw.Close(); 
4

2 に答える 2

3

このメソッドは、LINQ を使用HtmlNodeして、名前を持つインスタンスをクエリしますtd

val|val|また、出力が(末尾のパイプを使用string.Join(pipe, array)して) のように表示されることにも気付きましたval|val

using System.Linq;

// ...

var tablecollection = doc.DocumentNode.SelectNodes("//table");
string store = string.Empty;

if (tablecollection != null)
{
    foreach (HtmlNode table in tablecollection)
    {
        // For all rows with at least one child with the 'td' tag.
        foreach (HtmlNode row in table.DescendantNodes()
            .Where(desc =>
                desc.Name.Equals("tr", StringComparison.OrdinalIgnoreCase) &&
                desc.DescendantNodes().Any(child => child.Name.Equals("td",
                    StringComparison.OrdinalIgnoreCase))))
        {
            // Combine the child 'td' elements into an array, join with the pipe
            // to create the output in 'val|val|val' format.
            store = string.Join("|", row.DescendantNodes().Where(desc =>
                desc.Name.Equals("td", StringComparison.OrdinalIgnoreCase))
                .Select(desc => desc.InnerText));

            // You can probably get rid of the 'store' variable as it's
            // no longer necessary to store the value of the table's
            // cells over the iteration.
            sw.Write(store);
            sw.WriteLine();
        }
    }
}

sw.Flush();
sw.Close(); 
于 2012-08-28T23:23:19.853 に答える
3

XPath 構文が正しくありません。してみてください:

HtmlNode cell in row.SelectNodes("//td")

tdこれにより、 で反復できる要素のコレクションが取得されforeachます。

于 2012-08-28T22:21:22.683 に答える