3

I am getting this HTML string from DB :-

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex</p><img class="classname" alt="alttext" src="http://www.domain.com/uploads/myimage.jpg" width="612" height="612" /><p>Going by the Itinerary, we will be at the official launch on the 22nd May.</p><img class="classname" alt="alttext" src="http://www.domain.com/uploads/myimage1.jpg" width="612" height="612" />

As you can see that in string there is two image tags. I want to get the first image tag's source for eg :-

http://www.domain.com/uploads/myimage.jpg

can anyone suggest me how can get this text from html string.

Thanks in advance

Sandeep Tawaniya
  • 717
  • 8
  • 17

3 Answers3

14

You can use an html parser like HtmlAgilityPack for this

string html = .......
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
var link = doc.DocumentNode.SelectSingleNode("//img").Attributes["src"].Value;
carla
  • 1,970
  • 1
  • 31
  • 44
I4V
  • 34,891
  • 6
  • 67
  • 79
  • Spike beated you by 7 minutes ;) – dasheddot May 21 '13 at 07:46
  • 2
    @dasheddot So? Instead of giving link-only answer, I posted also a *working* code specific to the OP's case. – I4V May 21 '13 at 07:54
  • [*@Edit reviewers*](https://stackoverflow.com/review/suggested-edits/18043845) - the changed URL is valid; visit the initial link and see the project is moved to a domain, pointed to by the initial source. – Al.G. Nov 23 '17 at 16:47
3

I would recommend HTML Agility pack: http://htmlagilitypack.codeplex.com/wikipage?title=Examples There's an example even showing how to do it.

Jochen van Wylick
  • 5,303
  • 4
  • 42
  • 64
1

Use string.Substring to find the word src.

Remember Position of its occurrence.

Then again You can also use this in order to check, when the "" embedded string ends.

Paolo Stefan
  • 10,112
  • 5
  • 45
  • 64
icbytes
  • 1,831
  • 1
  • 17
  • 27