如何在C#中选择所有子代的dl标签

时间:2018-08-09 15:58:41

标签: c# html-agility-pack

我在从打击HTML表中选择所有dtdd时遇到问题

<dl class="Grid Grid--multicol Grid--2col:40em Grid--4col:60em">
    <div class="Grid-cell u-flex u-flexOne u-flexRow">
        <dt> Item ID:</dt>
        <dd class="u-weightSemibold u-paddingL5px">72547664</dd>
    </div>
    <div class="Grid-cell u-flex u-flexOne u-flexRow">
            <dt> License:</dt>
            <dd class="u-weightSemibold u-paddingL5px">
                <a class="u-linkDodgerBlue js-infoLicenseString" href="" target="_blank">Standard</a>
            </dd>
    </div>
    <div class="Grid-cell u-flex u-flexOne u-flexRow">
            <dt> Usage:</dt>
            <dd class="u-weightSemibold">Commercial<span class="TooltipQuestionMark"></span></dd>
    </div>
    <div class="Grid-cell u-flex u-flexOne u-flexRow">
            <dt> Required Plugins:</dt>
            <dd class="u-weightSemibold u-paddingL5px">None</dd>
    </div>
    <div class="Grid-cell u-flex u-flexOne u-flexRow">
            <dt> Creation Tool:</dt>
            <dd class="u-weightSemibold u-paddingL5px">Autodesk</dd>
    </div>
    <div class="Grid-cell u-flex u-flexOne u-isHidden:0-60em"></div>
</dl>

我写这个

            i = 0; doc.DocumentNode.SelectNodes("//dl").Where(x => x.HasClass("Grid")).FirstOrDefault().SelectNodes(".//div").ToList().ForEach(x =>
            {
                result.Items.Add(new DownloadItem { Name = "specs-title", Index = i,    Type = DownloadItemType.Text, Value = x.SelectNodes(".//dt").FirstOrDefault().GetText() });
                result.Items.Add(new DownloadItem { Name = "specs",       Index = i++,  Type = DownloadItemType.Text, Value = x.SelectNodes(".//dd").GetText() });
            });

上面的代码只占第一行 Item ID: | 72547664 列出所有dtdd信息的问题是什么

1 个答案:

答案 0 :(得分:0)

您的代码的问题是,当您第一次想获取类dl的所有Grid元素时,只能使用方法{{1}来获取这种类型的DOM元素中的第一个。 }。

FirstOrDefault()

您必须删除i = 0; doc.DocumentNode.SelectNodes("//dl").Where(x => x.HasClass("Grid")).SelectNodes(".//div").ToList().ForEach(x => { result.Items.Add(new DownloadItem { Name = "specs-title", Index = i, Type = DownloadItemType.Text, Value = x.SelectNodes(".//dt").FirstOrDefault().GetText() }); result.Items.Add(new DownloadItem { Name = "specs", Index = i++, Type = DownloadItemType.Text, Value = x.SelectNodes(".//dd").GetText() }); }); 才能使用所有适合您需求的元素。