【问题标题】:How to read HTML template, replace text and convert back to HTML如何阅读 HTML 模板、替换文本并转换回 HTML
【发布时间】:2019-11-24 23:01:38
【问题描述】:

我目前正在从文件路径加载一个 html 文件并将其作为文本读取。然后我替换文件本身中的某些字符,我想将它转换回 html。

这就是我目前的做法:

HtmlDocument document = new HtmlDocument();
document.Load(@message.Location);
content = document.DocumentNode.OuterHtml;

//Code to replace text

var eContent = HttpUtility.HtmlEncode(content);

当我调试并检查 eContent 包含的内容时,我可以看到像“\r\n”这样的换行符。如果我将文本复制并粘贴到 .html 文件中,则只会出现文本,而不是正确的 html 页面。

我已经在使用 Html AgilityPack,但不确定我还需要做什么。

编辑:

我也试过了

var result = new HtmlString(content);

【问题讨论】:

    标签: c# html .net asp.net-core html-agility-pack


    【解决方案1】:

    尝试使用ContentResult,它继承了ActionResult。请记住将ContentType 设置为text/html

    [HttpGet]
    public IActionResult FileToTextToHtml()
        {
            string fileContents = System.IO.File.ReadAllText("D:\\HtmlTest.html");
    
            var result= new ContentResult()
            {
                Content = fileContents,
                ContentType = "text/html",
            };
            return result;
        }
    

    【讨论】:

      【解决方案2】:

      我在使用之前已经这样做了......

       string savePath = "path to save html file, ie C://myfile.html";
      
       string textRead = File.ReadAllText(@"Path of original html file");
        //replace or manipulate as needed... ie textRead = textRead.Replace("", "");
       File.WriteAllText(savePath, textRead);
      

      【讨论】:

      • 是的,但我不想将其写入文件。我需要通过另一个函数发送字符串。
      • 然后删除 File.WriteAllText 并将字符串 textRead 传递到您想要的任何地方,它将保留其所有标签和 HTML 格式。
      【解决方案3】:

      HtmlAgilityPack 非常适合读取和修改您无法创建可读输出的 Html 文件。

      Try with this

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-02-21
        • 2015-06-11
        • 1970-01-01
        • 2021-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多