HtmlAgilityPack - How to select first a tag href while using selectnodes

Viewed 136

I'm trying to select the first tag and get the href value. But the problem is I'm using SelectNodes.

Here is the code i want to select a href value from:

<li>
<a class="img" href="link1"></a>
<div class="m_text">
<a class="title" href="link2" rel="27418">A Story</a>
<p><span class="stars star45"></span><span class="rate">4.35</span></p>
<p class="info" title="Action"></p>
<p class="nowrap latest"><a href = "link3" >< span class="nowrap">A Story</span> 29</a></p>
</div>
</li>

<li>
<a class="img" href="link1"></a>
<div class="m_text">
<a class="title" href="link2" rel="27418">A Story</a>
<p><span class="stars star45"></span><span class="rate">4.35</span></p>
<p class="info" title="Action"></p>
<p class="nowrap latest"><a href = "link3" >< span class="nowrap">A Story</span> 29</a></p>
</div>
</li>

Now as you see i have to select the first href value of a tag for multiple times and then i will use foreach.

The html i want to get value is :

<a class="img" href="link1"></a>

My code:

 var documentx = new HtmlWeb().Load(post.ExtLink);
        var div = documentx.DocumentNode.SelectNodes("//div[@id='content']/*//ul[@class='list']//li");

        var test = div.Descendants("a")
                            .Select(a => a.GetAttributeValue("href", null))
                            .Where(s => !String.IsNullOrEmpty(s))
                            .ToList();

My code works fine but it's get all the a tag values and i only looking to get the first a tag href value.

1 Answers

Change

.Where(s=> !String.IsNullOrEmpty(s))

To

.FirstOrDefault(s=> !String.IsNullOrEmpty(s))

And remove the .ToList() at the end.

Related