1

List consists from Title (Single line of text) and Content (Multiple lines of text - Enhanced rich text) columns.

I need to get snippet from Content column(~125 first symbols). I've found that text in Content column formatted and contains html tags. I want to know, how I can programmatically get plain text from rich text? I know that I can use Regex, but it's not nice solution.

Have an answer?

3 Answers 3

5

Didn't test, but you can probably use SPFieldMultiLineText.GetFieldValueAsText Method :

SPListItem yourItem = ....; // obtain the SPListItem with any method
SPFieldMultiLineText field = (SPFieldMultiLineText)yourItem.Fields["Content"]; 

string text = field.GetFieldValueAsText (yourItem["Content"]);
3

If you dont want to use this

string content = Regex.Replace(textWithHTML, "<.*?>", string.Empty);

you can use this, this returns the SPListItem as normal text

private string getFieldAsText(SPListItem item, string fieldName, string captionName)
{
            return ReferenceEquals(item[fieldName], null) ? string.Empty :
                item.Fields[captionName].GetFieldValueAsText(item[fieldName]);
}
0

This is probably what you need:

const string htmlRegex = "<.*?>";

static string StripHTML (string inputString)
{
   // Removes all the HTML tags and returns the string with the 125 first characters
   return Regex.Replace(inputString, htmlRegex, string.Empty).Remove(125);
}
3
  • is there a solution without further processing? I mean is there method extracting plain text from SPListItem?
    – user6339
    Commented Jan 12, 2012 at 10:39
  • @Nurlan Not that I am aware of, no.
    – user2536
    Commented Jan 12, 2012 at 10:41
  • @Nurlan Yes, see the answers. While this might work, I prefer the other methods.
    – Kit Menke
    Commented Jan 12, 2012 at 15:58

Your Answer

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