8

Can Html Agility Pack be used to parse an html string fragment?

Such As:

var fragment = "<b>Some code </b>"; 

Then extract all <b> tags? All the examples I seen so far have been loading like html documents.

1
  • 1
    It could be done even simlier with HAP, in one line: var text = HtmlNode.CreateNode("<b>Some code </b>").InnerText; Commented Mar 4, 2012 at 15:31

3 Answers 3

11

If it's html then yes.

string str = "<b>Some code</b>"; // not sure if needed string html = string.Format("<html><head></head><body>{0}</body></html>", str); HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(html); // look xpath tutorials for how to select elements // select 1st <b> element HtmlNode bNode = doc.DocumentNode.SelectSingleNode("b[1]"); string boldText = bNode.InnerText; 
Sign up to request clarification or add additional context in comments.

4 Comments

Ok then what would I do with it how would I do some parsing?
Hmm thanks but I copied and pasted that code into a console app and imported html agility back but on HtmlNode line I get a null reference exception.
Maybe it's HtmlNode bNode = doc.DocumentNode.SelectSingleNode("/b[1]");
Try HtmlNode bNode = doc.DocumentNode.SelectSingleNode("//b[1]");
2

I dont think this is really the best use of HtmlAgilityPack.

Normally I see people trying to parse large amounts of html using regular expressions and I point them towards HtmlAgilityPack but in this case I think it would be better to use a regex.

Roy Osherove has a blog post describing how you can strip out all the html from a snippet:

Even if you did get the correct xpath with Mika Kolari's sample this would only work for a snippet with a <b> tag in it and would break if the code changed.

Comments

0

This answer came up when I searched for the same thing. I don't know if the features have changed since it was answered but this below should be better.

$string = '<b>Some code </b>' [HtmlAgilityPack.HtmlNode]::CreateNode($string) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.