0

我从目录表中提取链接,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);
        }
4

1 回答 1

0

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

于 2016-08-10T16:11:39.147 回答