Convertir rtf a xml en C #

En la continuación de una serie de publicaciones sobre la conversión de archivos de texto a xml usando C #, propongo pasar a convertir archivos rtf .


Parece que este formato es bastante antiguo y está muy extendido, y si no hay ninguna biblioteca para convertir todos los datos al formato xml llamando a un método, definitivamente debe haber algún tipo de solución de Microsoft, al menos similar a OpenXML . Sin embargo, si lo fuera, entonces este artículo no habría sido escrito.


Entonces, ¿qué es un archivo ReachTextFile (rtf) ? En general, el contenido del archivo ya está estructurado e incluso recuerda una mezcla de json, xml y xpath. Esto se puede verificar fácilmente guardando un documento de Word en formato rtf y luego intentando leerlo en un editor de texto como Notepad ++ :



Destaqué en rojo una parte del archivo que contiene información sobre la codificación: en general, las etiquetas están encriptadas con codificación ansi, y el texto en sí está codificado con ansicpg1251. El texto en sí se ve así:



, , , , … , , , , php.


, , , , , , , . - .


, , , rtf RichTextBox, :


  • -, Windows.Forms, .
  • -, . , RichTextBox , , .

, nuget RtfPipe. .


RtfPipe . rtf html. , HtmlAgilityPack.


, - ? : , , , , . , rtf- , , , , — , , , , , .


, .


public string Convert(Stream stream)
        {
            stream.Position = 0;
            string rtf = string.Empty;
            using (StreamReader sr = new StreamReader(stream))
            {
                rtf = sr.ReadToEnd();
            }
            //      RtfPipe  Core 
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            //    RtfPipe  html
            var html = Rtf.ToHtml(rtf);
            //  html     ,   xml
            return ClearHtml(html);
        }

  1. string. RtfPipe. ,
  2. , .Net Core Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);. RtfPipe. .
    .Net Framework, .
  3. var html = Rtf.ToHtml(rtf); — html . , , , ( ), .


string ClearHtml(string html), xml:


string ClearHtml(string html)
{
    //  html   HtmlAgilityPack
    HtmlDocument doc = new HtmlDocument();
    doc.LoadHtml(html);
    //    (),     style
    var elementsWithStyleAttribute = doc.DocumentNode.SelectNodes("//@style");
    //   ,    
    var excessNodes = doc.DocumentNode.SelectNodes("//b|//u|//strong|//br");
    //     html
    foreach (var element in excessNodes)
    {
        element.ParentNode.InnerHtml = element.InnerText;
        element.Remove();
    }
    foreach (var element in elementsWithStyleAttribute)
    {
        element.Attributes["style"].Remove();
    }
    //    html
    using (StringWriter writer = new StringWriter())
    {
        doc.Save(writer);
        html = writer.ToString();
    }
    //   html  xml
    StringBuilder xml = new StringBuilder();
    xml.Append("<?xml version=\"1.0\"?><documents><document>");
    xml.Append(html);
    xml.Append("</documents></document>");
    return xml.ToString();
}

  1. , HtmlAgilityPack nuget
  2. doc HtmlDocument html
  3. , , . , style, , , , .
  4. C , StringBuilder xml, .

, , , .



docx xlsx


All Articles