AngleSharp在Span之后无法获得NextSibling

时间:2016-08-10 15:09:04

标签: c# html anglesharp

我从内容表的表中提取链接,id =“toc”并将每个链接传递给方法。在方法内部,我试图按照书签(Span标签)到达表,但代码一直为NextSibling和NextElementSibling返回null。下面是我的html和我的C#代码。

<table id="toc" class="toc">
  <tr>
    <td>
      <div id="toctitle">
        <h2>Contents</h2>
      </div>
      <ul>
        <li class="toclevel-1 tocsection-1"><a href="#DEV_Environment"><span class="tocnumber">1</span> <span class="toctext">DEV Environment</span></a>
        </li>
      </ul>
    </td>
  </tr>
</table>
<h2> <span class="mw-headline" id="DEV_Environment"> DEV Environment </span></h2>
<table border="1" cellpadding="2">
  <tr>
    <th scope="col" style="width: 225px; background: #6EB4EB">CDR IP
    </th>
    <th scope="col" style="width: 225px; background: #6EB4EB">Client FEP IP:Port
    </th>
    <th scope="col" style="width: 225px; background: #6EB4EB">CHCS IP
    </th>
  </tr>
  <tr style="text-align:center;">
    <td>###.##.##.###</td>
    <td>###.##.##.###:#####</td>
    <td>###.##.##.##
    </td>
  </tr>

    public void LoadCdrs()
    {
        try
        {
            WebClient webClient = new WebClient();

            /** refreshToken is bogus, but it prevents caching of the data so we always get the latest **/
            string html = webClient.DownloadString(environmentsUrl + "?refreshToken=" + Guid.NewGuid().ToString());
            HtmlParser htmlParser = new HtmlParser();
            IDocument document = htmlParser.Parse(html);

            IElement toc = document.GetElementById("toc");
            IHtmlCollection<IElement> tocLinks = toc.QuerySelectorAll("li");
            foreach (IElement element in tocLinks)
            {
                IElement anchor = element.FirstElementChild;
                Cdr environmentInfo = new Cdr(anchor, null, null);
                Add(environmentInfo);
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

 public Cdr(IElement anchor, Object lcs, Object snarePort) : base()
    {
        try
        {
            Name = anchor.Children[1].TextContent;
            string[] hrefParts = anchor.GetAttribute("href").Split('#');
            string href = hrefParts[hrefParts.Length - 1];
            var element = anchor.Owner.GetElementById(href);
            while (!element.TagName.Equals("table", StringComparison.CurrentCultureIgnoreCase))
            {
                if (element.NextSibling != null)
                {
                    element = element.ParentElement.NextElementSibling;
                }
                else
                {
                    element = element.NextElementSibling;
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

1 个答案:

答案 0 :(得分:0)

确定。我发现了这个问题。我在代码中的错误。在Cdr构造函数方法的while循环中,If语句应该是“if(element.NextSibling == null)而不是”!=“不等于null。对不起那些人。