Convertir rtf en xml en C #

Dans la suite d'une série d'articles sur la conversion de fichiers texte en xml en C #, je propose de passer à la conversion de fichiers rtf .


Il semblerait que ce format soit assez ancien, et il est très répandu, et s'il n'y a pas de bibliothèque pour convertir toutes les données au format xml en appelant une méthode, alors il doit certainement y avoir une sorte de solution de Microsoft, au moins similaire à OpenXML . Si tel était le cas, cet article n'aurait pas été écrit.


Qu'est-ce qu'un fichier ReachTextFile (rtf) ? Dans l'ensemble, le contenu du fichier est déjà structuré et rappelle même un mélange de json, xml et xpath. Cela peut être facilement vérifié en enregistrant certains documents Word au format rtf , puis en essayant de les lire dans un éditeur de texte tel que Notepad ++ :



J'ai mis en évidence en rouge une partie du fichier qui contient des informations sur l'encodage: en général, les balises sont cryptées avec l'encodage ansi, et le texte lui-même est encodé avec ansicpg1251. Le texte lui-même ressemble à ceci:



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