C# 在 html 文件中将 < 替换为 <

C# Replace &lt; with < in a html file

我正在尝试制作一个单词导出功能,但我的内容有 html 标签。我把这个内容放在html文件里,他们把<换成了&lt;,那不是我想要的。

有人可以帮我解决这个问题吗?

我使用 office interop word,这是我现在使用的代码:

Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

Document doc = app.Documents.Open(FileName: @"C:\Users\example\Documents\Template.docx", ReadOnly: false);
app.Selection.Find.Execute("<Index>");
app.Selection.TypeText("<h1>hello</h1>");

doc.SaveAs2(@"C:\Users\krisb\Documents\voorbeeld.html", FileFormat: WdSaveFormat.wdFormatWebArchive);
doc.Close();

Document doc1 = app.Documents.Open(FileName: @"C:\Users\example\Documents\voorbeeld.html", ReadOnly: false);
app.Selection.Find.Execute("&lt;");
app.Selection.TypeText("<");
app.Selection.Find.Execute("&gt;");
app.Selection.TypeText(">");

doc1.SaveAs2(@"C:\Users\example\Documents\template.docx", FileFormat: WdSaveFormat.wdFormatDocumentDefault);
doc1.Close();

Document doc2 = app.Documents.Open(FileName: @"C:\Users\example\Documents\kristemplate.docx", ReadOnly: false);
doc2.SaveAs2(@"C:\Users\example\Documents\kristemplate.pdf", FileFormat: WdSaveFormat.wdFormatPDF);

app.Quit();`

Word 不是 HTML 编辑器,因此您不能告诉它直接使用特定的 HTML 标签。 Word 只能导入导出 HTML 文件。在内部,Word 对象模型将它们视为 Word 文档。

可能的工作是插入"Hello"以HTML导出将其呈现为的方式格式化它h1。我完全不知道这是否可行,但将您的文本格式化为 "Heading 1" 可能是个不错的猜测。

或者,如果您需要直接修改生成的HTML,您应该

  • 首先将文件导出为 HTML,然后 然后
  • 在 C# 中将其作为文本文件打开并进行替换。