Why does HtmlParser remove the line break tags?

Viewed 161

I'm using this HtmlFromXamlConverter from Microsoft and trying to display html script on a RichTextBox. HtmlToXamlConverter is working fine but HtmlFromXamlConverter isn't.

Example:

#Part.143
<p><b><font size="5">Wundklassifikation Diabetisches Fußsyndrom nach Wagner</font></b></p>
<b>Grad 0</b><br>Keine Läsion, evtl. Fußdeformation oder Cellulitis<br><br>
<b>Grad 1</b><br>Oberflächliches Ulkus<br><br>
<b>Grad 2</b><br>Tiefes Ulkus bis zur Gelenkkapel<br><br>
<b>Grad 3</b><br>Tiefes Ulkus mit Abszedierung, Osteomyelitis, Infektion der Gelenkkapsel<br><br>
<b>Grad 4</b><br>Begrenzte Vorfuß- oder Fersennekrose<br><br>
<b>Grad 5</b><br>Nekrose des gesamten Fußes<br><br>

If I convert this html script to XAML script using the HtmlToXamlConverter, it is shown on the RichTextBox as follows: Screenshot from RichTextBox

And then when I convert it back from XAML to html using HtmlFromXamlConverter and use the generated html code to display it on RichTextBox, it is shown on the RichTextBox as follows: Screenshot from RichTextBox (line breaks are no longer included)

This is the c# code that I use to convert from and to XAML

Convert from html to Xaml:

if(XamlReader.Parse(HtmlToXamlConverter.ConvertHtmlToXaml(File.ReadAllText(@"C:\Users\XXX\Documents\testHtml.html"), true)) is FlowDocument flowDoc)
{
           
      RichTextBox.Document = flowDoc;
}

Convert back from Xaml to html:

string str1 = XamlWriter.Save(RichTextBox.Document);
string str = XamlToHtmlConverter.ConvertXamlToHtml(str1);

I have been trying for a long time and no success. I am grateful for help

1 Answers

Looks like this is a case of the converters not being symmetrical.

Try this:

  • Find in Files (Ctrl-Shift-F on Visual Studio), and search for "Paragraph". You'll see that it has matches in both ToXaml and FromXaml. They are responsible for converting <p> to <Paragraph> and vice versa.
  • Now look for "LineBreak". This is the cause of your issue; it only exists in ToXaml but not the other way around.

The solution is simply to add a LineBreak handler in HtmlFromXamlConverter. Just add it next to the Paragraph handler.

case "Paragraph":
    htmlElementName = "p";
    break;
// Add these:
case "LineBreak":
    htmlElementName = "br";
    break;

That should do it.

NOTE: I hope you're not using <hr> cause that's another one that wouldn't work, and will be harder to fix.

Related