我有一块html,看起来像这样;C#替换多个href值
<p><a href="docs/123.pdf">33</a></p>
基本上有数百个锚链接,我需要根据锚文本替换href。例如,我需要用类似的东西替换上面的链接;
<a href="33.html">33</a>.
我将需要取值33,并对我的数据库进行查找以找到新的链接来替换href。
我需要把它全部保留在上面的原始HTML!
我该怎么做?帮帮我!
我有一块html,看起来像这样;C#替换多个href值
<p><a href="docs/123.pdf">33</a></p>
基本上有数百个锚链接,我需要根据锚文本替换href。例如,我需要用类似的东西替换上面的链接;
<a href="33.html">33</a>.
我将需要取值33,并对我的数据库进行查找以找到新的链接来替换href。
我需要把它全部保留在上面的原始HTML!
我该怎么做?帮帮我!
啜你的HTML到XmlDocument(您的标记是有效的,不是吗?),然后使用XPath找到具有href
属性的所有<a>
标签。应用变换并将新值分配给href
属性。然后写出XmlDocument。
简单!
尽管这不会回答你的问题,在HTML敏捷性包是操作和工作的好工具与HTML:http://html-agility-pack.net
它至少可以抓住你需要的价值观,并做更换更容易一些。
包含链接使用HTML敏捷性包:How to use HTML Agility pack
我使用了敏捷包,取得了巨大成功。正则表达式的问题是,如果标记不正确,您可能会错过或错过命中。 HTML敏捷性包正是OP所需的。 – SRM 2011-06-07 22:48:24
考虑使用以下粗略的算法。
using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
static class Program
{
static void Main()
{
string html = "<p><a href=\"docs/123.pdf\">33</a></p>"; // read the whole html file into this string.
StringBuilder newHtml = new StringBuilder (html);
Regex r = new Regex (@"\<a href=\""([^\""]+)\"">([^<]+)"); // 1st capture for the replacement and 2nd for the find
foreach (var match in r.Matches(html).Cast<Match>().OrderByDescending(m => m.Index))
{
string text = match.Groups[2].Value;
string newHref = DBTranslate (text);
newHtml.Remove (match.Groups[1].Index, match.Groups[1].Length);
newHtml.Insert (match.Groups[1].Index, newHref);
}
Console.WriteLine (newHtml);
}
static string DBTranslate(string s)
{
return "junk_" + s;
}
}
(该OrderByDescending确保为您修改StringBuilder的指标并没有改变。)
所以,你想要做的是根据匹配的内容生成替换字符串。请考虑使用MatchEvaluator的Regex.Replace
过载之一。例如:
static void Main()
{
Regex r = new Regex(@"<a href=""[^""]+"">([^<]+)");
string s0 = @"<p><a href=""docs/123.pdf"">33</a></p>";
string s1 = r.Replace(s0, m => GetNewLink(m));
Console.WriteLine(s1);
}
static string GetNewLink(Match m)
{
return string.Format(@"(<a href=""{0}.html"">{0}", m.Groups[1]);
}
其实我已经采取了一步,并使用了lambda expression而是明确创建一个委托方法。
已更新,让你看到html :-) – lordy1981 2011-06-07 22:37:30
你有HTML或有效的XML吗? – ulrichb 2011-06-07 22:40:50
你是动态生成这个HTML(网络服务器)还是只是想用命令行或Windows可执行文件周期性地/周期性地生成这个文件?另外,您是否需要在现有文档中“替换”它们,还是可以重新生成整个文档? – 2011-06-07 23:23:28