How to select a dl tag with all child in c#

c# html-agility-pack

Question

I have a problem to select all dt and dd from the blow HTML table

<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 write this

            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() });
            });

The above code just grab the first row Item ID: | 72547664 whats my problem to list all dt and dd information

Accepted Answer

the problem of your code is that at first time when you want to grab all dl elements with class Grid, you take only first of that type of DOM elements with the method 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() });
            });

you have to remove FirstOrDefault() to take all the elements which suits to your demand.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why