在html文件中查找和替换文本

时间:2014-02-11 10:36:13

标签: c# html winforms 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);

但它不起作用。主要问题出现在正在使用的双引号逗号中。怎么办呢?

2 个答案:

答案 0 :(得分:1)

据我所知,您将在LINK中拥有动态HTML页面网址。 为什么要尝试更改整个链接。

试试这个。在您的HTML中,使LINK类似于下面的内容,这些内容在您的页面中是唯一的,并且仅使用新的LINK替换该特定字符串。

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

在申请中

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

这应该可以完美地运作

答案 1 :(得分:0)

使用HtmlAgility包(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();