Converter rtf para xml em c #

Na continuação de uma série de postagens sobre a conversão de arquivos de texto em xml usando C #, proponho a conversão de arquivos rtf .


Parece que esse formato é bastante antigo, e muito difundido, e se não há nenhuma biblioteca para converter todos os dados em formato xml chamando um método, então definitivamente deve haver algum tipo de solução da Microsoft, pelo menos semelhante ao OpenXML . No entanto, se fosse, esse artigo não teria sido escrito.


Então, o que é um arquivo ReachTextFile (rtf) ? De um modo geral, o conteúdo do arquivo já está estruturado e até lembra uma mistura de json, xml e xpath. Isso pode ser facilmente verificado salvando algum documento do Word no formato rtf e tentando lê-lo em um editor de texto como o Notepad ++ :



Eu destaquei em vermelho uma parte do arquivo que contém informações sobre a codificação: em geral, as tags são criptografadas com a codificação ansi e o próprio texto é codificado com ansicpg1251. O texto em si é assim:



, , , , … , , , , 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