简体   繁体   中英

c# htmlagility select specific xpath

i have this html code :

<div>
<time class="departure"><span></span>value1<time class="return">
<span></span>value2</time>
</div>

i'm using the c# code below :

    var nodes = doc.DocumentNode.SelectNodes("//time[@class='departure']");
    foreach (var node in nodes)
    {

        Console.WriteLine(node.InnerHtml);
        if (node.InnerText.Trim() == DepartTime)
        {
            ReturnTime = node.SelectSingleNode("time").InnerText; //null reference here 
        }
    }

so as you can see i'm checking if the depart time (DepartTime) exist then it will returns the next innertext value of the first time element after . but this doesnt seems to be working i get exception null reference .

solved it by

    foreach (var node in nodes)
    {
        if (node.InnerText.Trim() == DepartTime)
        {
            ReturnTime = node.ParentNode.SelectNodes("time")[1].InnerText.Trim();
        }
    }

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