Share via


XML Highlight in RichTextBox

 

Recently I’ve been looking for some piece of code that would perform XML highlighting in a Rich Text Box. The Internet provides several free samples and several commercial samples but I wasn’t really satisfied with what I found, mainly because it involved using an XMLTextReader object, which does not help for WYSWYG editing of the XML file.

So I created a simple C# function that formats the text content from a RichTextBox:

public static void HighlightRTF(RichTextBox rtb)

The complexity is roughly O( n ), where n is the number of characters in the XML file.

Here is the result:

image

You’ll find the function in the text attachment.

highlightRTF.txt

Comments

  • Anonymous
    January 04, 2012
    Nice - Been trying this for the past few days now with no luck. Thanks!

  • Anonymous
    February 24, 2012
    Nice work. Angle brackets should be in blue though.

  • Anonymous
    August 29, 2012
    Perfect stuff

  • Anonymous
    September 24, 2012
    Good stuff....finally found what I want.....thanks

  • Anonymous
    October 27, 2012
    how can i convert this class to dll file i tried but i can't?

  • Anonymous
    September 10, 2013
    The comment has been removed

  • Anonymous
    April 14, 2014
    It is not working for WPF C# properly. Can you please help me on this?

  • Anonymous
    April 14, 2014
    I have changed for RichTextBox text like:TextRange allTextRange = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);string str = allTextRange.Text;and took the range as like:allTextRange.Select(start.GetPositionAtOffset(lasten + 1), start.GetPositionAtOffset(st));                    allTextRange.ApplyPropertyValue(TextElement.ForegroundProperty,HighlightColors.HC_INNERTEXT);Although its not showing properly. I am applying text in RichBoxText by XMLDocument like belowXmlDocument doc = new XmlDocument();doc.Load(parentRef."FilePath.xml);gameListXMLText.Document.Blocks.Clear();gameListXMLText.AppendText(doc.InnerXml.ToString());HighlightRTF(gameListXMLText);So please let me know, where i am doing wrong?

  • Anonymous
    April 23, 2014
    Consider the Nevron Rich Text Editor control (www.nevron.com/products-open-vision-nov-rich-text-editor-control-overview.aspx) works in WPF, Siliverlight and WinForm apps...

  • Anonymous
    February 22, 2015
    I made a subclass of RichTextBox and put your code in the TextChanged event handler.

  • Anonymous
    May 25, 2015
    The file is truncated! Thus useless...

  • Anonymous
    August 06, 2015
    Thanks Costin Boldisor, that was a real help , and is working great.

  • Anonymous
    November 08, 2015
    Hi! Anyone having the file? it seems that it has got truncated when i try to download it :(

  • Anonymous
    January 25, 2016
    Great!, But the Complexity of O(n) takes too long.

  • Anonymous
    May 16, 2016
    Amazing! Thanks!

  • Anonymous
    January 14, 2017
    This is amazing, thank you so much!