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();
}
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var html = Rtf.ToHtml(rtf);
return ClearHtml(html);
}
- string.
RtfPipe
. , - , .Net Core
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
. RtfPipe. .
.Net Framework, . var html = Rtf.ToHtml(rtf);
— html . , , , ( ), .

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