C#一次获取所有子节点

时间:2018-10-24 08:58:35

标签: c# html

我正在尝试获取Wikitable的第2行(标题)。尤其是以下链接中“ Lista Episodi”下的表格:https://it.wikipedia.org/wiki/Episodi_di_Dragon_Ball_Super 第一行是:

<table class="wikitable" style="width:auto">
 <tbody> 
  <tr>
    <th style="width:auto;white-space:nowrap" rowspan="2">Nº
    </th>
    <td style="background:#eaecf0;text-align:left;width:auto" rowspan="2">
     <b><a title="Lingua italiana" href="/wiki/Lingua_italiana">Titolo italiano</a>
     </b> 
     <br>
     <b>
      <a title="Lingua giapponese" href="/wiki/Lingua_giapponese">Giapponese</a>
     </b> 
     「
     <i>
      <b><a title="Kanji" href="/wiki/Kanji">Kanji</a></b></i>
     」 - 
     <i>
      <b>
       <a title="Rōmaji" href="/wiki/R%C5%8Dmaji">Rōmaji</a>
      </b>
     </i>
      - 
     <b>
      <a title="Traduzione" href="/wiki/Traduzione">Traduzione letterale</a>
     </b>
    </td>
    <th colspan="2">In onda</th>
   </tr>
 </tbody>
</table>

我有一个工作代码,可以正确获取整个标头并将其放在列表中:

HtmlDocument doc = new HtmlDocument();
        string page = "https://it.wikipedia.org/wiki/Episodi_di_Modern_Family_(prima_stagione)";
        string page1 = "https://it.wikipedia.org/wiki/Episodi_di_Dragon_Ball_Super";
        StreamReader reader;
        reader = new StreamReader(WebRequest.Create(page1).GetResponse().GetResponseStream(), Encoding.UTF8);               
        doc.Load(reader);
List<List<string>> header = doc.DocumentNode.SelectSingleNode("//table[@class='wikitable']").Descendants("tr")
            .Where(ld => ld.Elements("th").Count() > 0)
            .Select(ld => ld.Elements("th").Select(td => td.InnerText.Trim()).ToList()).ToList();

不幸的是,在此表中也有一个td节点,而不是只有th节点,即使它是一排标题也是如此。先前的代码只能读取第一个节点。 如何同时获取第二个节点和td节点?我尝试过类似的事情:

List<List<string>> header = doc.DocumentNode.SelectSingleNode("//table[@class='wikitable']").Descendants("tbody")
            .Where(ld => ld.Elements("tr").Count() > 0)
            .Select(ld => ld.Elements("tr").Select(td => td.InnerText.Trim()).ToList()).ToList();

它获取所有3个子节点,但将3个内容放到单个字符串中。你能帮我吗?

1 个答案:

答案 0 :(得分:0)

您获取tr标签的内容,但需要将其扁平化。尝试这样的事情:

List<List<string>> header2 = doc.DocumentNode.SelectSingleNode("//table[@class='wikitable']")
    .Descendants("tr")
    .Select(x=>x.ChildNodes
        .Select(c=>c.InnerText.Trim())
        .Where(y=>!string.IsNullOrWhiteSpace(y))
        .ToList())
    .ToList();