簡體   English   中英

查找和替換html文件中的文本

[英]Find and Replace text in html file

我正在使用C#中的Winforms。 我有以下HTML文件。

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="generator" content="HTML Tidy for Windows (vers 25 March 2009), see www.w3.org" />
<meta http-equiv="Content-Type" content="text/html; charset=us-ascii" />
<link rel="stylesheet" type="text/css" href="styles.css" />
<title></title>
</head>
<body>
<p><b>Chapter 1</b></p>
</body>
</html>

而且我想將<link rel="stylesheet" type="text/css" href="styles.css" />替換為"<link rel="stylesheet" type="text/css" href=""+ htmlFile +"" />"我嘗試了以下代碼,但沒有用

 string outpageFile = File.ReadAllText(StaticClass.outpage);
            string htmlFile= StaticClass.ZipFilePath + "\\OEBPS\\styles.css";
            outpageFile = outpageFile.Replace("<link rel='stylesheet' type='text/css' href='styles.css' />", "<link rel='stylesheet' type='text/css' href='"+ htmlFile +"' />");
            File.WriteAllText(StaticClass.outpage, outpageFile);

但這行不通。 主要問題發生在正在使用的雙引號逗號中。 那怎么辦呢??

據我了解,您將在LINK中有一個動態HTML頁面網址。 為什么要嘗試更改整個鏈接。

嘗試這個。 在HTML中,使LINK如下所示,該LINK在您的頁面中將是唯一的,並用新的LINK替換該特定字符串。

<link rel="stylesheet" type="text/css" href='@MYLINK' />

在申請中

filenamestring.replace("@MYLINK","http://www.google.com");

這應該工作完美

使用HtmlAgility pack( http://htmlagilitypack.codeplex.com/ )-正則表達式不是處理html中替換項的最佳方法。

例:

      string markup = @"<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN""
    ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"">
<html xmlns=""http://www.w3.org/1999/xhtml"">
<head>
<meta name=""generator"" content=""HTML Tidy for Windows (vers 25 March 2009), see www.w3.org"" />
<meta http-equiv=""Content-Type"" content=""text/html; charset=us-ascii"" />
<link rel=""stylesheet"" type=""text/css"" href=""styles.css"" />
<title></title>
</head>
<body>
<p><b>Chapter 1</b></p>
</body>
</html>";
      var html = new HtmlAgilityPack.HtmlDocument();
      html.LoadHtml(markup);
      var links = html.DocumentNode.SelectNodes("//link");
      foreach (var link in links) {
        link.Attributes["href"].Value = StaticClass.ZipFilePath +
          "\\OEBPS\\styles.css";
      }

      var builder = new StringBuilder();
      using (var writer = new StringWriter(builder)) {
        html.Save(writer);
      }
      markup = builder.ToString();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM