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 (14)

  1. Scott says:

    Nice – Been trying this for the past few days now with no luck. Thanks!

  2. Kevin says:

    Nice work. Angle brackets should be in blue though.

  3. Kz says:

    Perfect stuff

  4. Aravind says:

    Good stuff….finally found what I want…..thanks

  5. Medo says:

    how can i convert this class to dll file i tried but i can't?

  6. Rich Text Box control says:

    The Rich Text Box control provides rich text formatting options, including bold, italic, underline, and text color etc., mail-merge and a variety of end-user options collection to edit the text content.

    http://www.kettic.com/…/richtextbox.shtml

  7. VarunUpadhyay says:

    It is not working for WPF C# properly. Can you please help me on this?

  8. VarunUpadhyay says:

    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 below

    XmlDocument 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?

  9. Bob Milanov says:

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

  10. Marcel van Pinxteren says:

    I made a subclass of RichTextBox and put your code in the TextChanged event handler.

  11. Mezzo says:

    The file is truncated!

    Thus useless…

  12. Samcolons says:

    Thanks Costin Boldisor, that was a real help , and is working great.

  13. Joachim Snellman says:

    Hi!

    Anyone having the file?

    it seems that it has got truncated when i try to download it 🙁

  14. Dan says:

    Great!, But the Complexity of O(n) takes too long.