0

I have a string which is basically a block of content with normal formatting (p tags, bold etc..) and sometimes contains HTML links editors have put in.

But I want to keep all the other HTML, but just strip out the links. But not sure the fastest and most efficient way of doing this as the string can be large (As they are Articles)

Any code sample greatly appreciated :)

4
  • you want the html with out hyperlinks? means plain text with formatting of p,bold, italic tags, right? Commented Nov 5, 2010 at 7:13
  • You want to do this server side (as in using PHP etc) or client side (just change the displayed HTML using Javascript)? Commented Nov 5, 2010 at 7:43
  • @JP19 - by virtue of the C#, I assume server or offline. Commented Nov 5, 2010 at 7:43
  • ...and now you have two problems... Commented Nov 5, 2010 at 7:44

1 Answer 1

3

Not very accurate, but a lazy apprach would be to replace "<a " with "<span " and "</a>" with "</span>". A more accurate result would be to parse it in a DOM:

string html;
using (var client = new WebClient()) {
    html = client.DownloadString("http://stackoverflow.com");
}
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
HtmlNode node;
// loop this way to avoid issues with nesting, mutating the set, etc
while((node = doc.DocumentNode.SelectSingleNode("//a")) != null) {
    var span = doc.CreateElement("span");
    span.InnerHtml = node.InnerHtml;
    node.ParentNode.InsertAfter(span, node);
    node.Remove();
}
string final = doc.DocumentNode.OuterHtml;

Note, however, that removing the link tags may change the styling, for example if there is a css style of the form a.someClass { ... } or a someNested {...}

Note on the code above; you could also try the more direct:

foreach(var node in doc.DocumentNode.SelectNodes("//a")) {
    var span = doc.CreateElement("span");
    span.InnerHtml = node.InnerHtml;
    node.ParentNode.InsertAfter(span, node);
    node.Remove();
}

but I wasn't sure if this might cause issues with mutation/iteration for some nesting constructs...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.