简体   繁体   中英

Parsing Radio buttons

I am having an issue parsing radio buttons for there value and the innertext on the span

Mark Up

<div id="First" class="Size-Inputs"> 
<input rel="8" type="radio" value="13051374" name="idProduct-13051359"/> <span rel="L">L</span>
<input rel="8" type="radio" value="13051373" name="idProduct-13051359"/> <span rel="M">M</span>
<input rel="8" type="radio" value="13051372" name="idProduct-13051359"/> <span rel="S">S</span>
<input rel="8" type="radio" value="13051375"name="idProduct-13051359"/> <span rel="XL">XL</span> </div>

The issue which I am having is the span name is only coming up with one letter at a time which is the "L". The value is working properly but I cannot figure out what is going wrong.

HtmlNodeCollection link = doc.DocumentNode.SelectNodes("//*[@id='First']/input");
//HtmlNodeCollection name = doc.DocumentNode.SelectNodes("//*[@id='First']/span");
if (link != null)
{
    foreach (HtmlNode item in link)
    {
        if (item != null)
        {
            string name = item.SelectSingleNode("//*[@id='First']/span").InnerText;
            string value = item.Attributes["value"].Value;
           Console.WriteLine(name);
           Console.WriteLine(value);
        }
    }
    Console.ReadLine();
}

I was just wondering whether anyone could give me any advice how to use the one Xpath then loop through all the span names and values of the radio buttons.So the console prints out all the span names and values. Thanks for any advice which you can give

You can try this way :

HtmlNodeCollection link = doc.DocumentNode.SelectNodes("//*[@id='First']/span");
if (link != null)
{
    foreach (HtmlNode item in link)
    {
        string name = item.InnerText;
        string value = item.SelectSingleNode("./preceding-sibling::input[1]").Attributes["value"].Value;
        Console.WriteLine(name);
        Console.WriteLine(value);
    }
    Console.ReadLine();
}

Basically XPath statement used to get value means : select <input> element that is direct preceding sibling of current <span> element, then get it's value attribute. The rest already explained here .

var links = htmlDoc.DocumentNode.SelectNodes("//*[@id='First']/input[@value]");
if (links != null)
{
    foreach (var link in links)
    {
        string value = link.Attributes["value"].Value;
         string name = null;
        var span = link.SelectSingleNode("following-sibling::span");
        if (span != null)
        {
            name = span.InnerText;
        }
         Console.WriteLine(name + " - " + value);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM