2011-06-07 35 views
1

我有一块html,看起来像这样;C#替换多个href值

<p><a href="docs/123.pdf">33</a></p> 

基本上有数百个锚链接,我需要根据锚文本替换href。例如,我需要用类似的东西替换上面的链接;

<a href="33.html">33</a>. 

我将需要取值33,并对我的数据库进行查找以找到新的链接来替换href。

我需要把它全部保留在上面的原始HTML!

我该怎么做?帮帮我!

+0

已更新,让你看到html :-) – lordy1981 2011-06-07 22:37:30

+0

你有HTML或有效的XML吗? – ulrichb 2011-06-07 22:40:50

+0

你是动态生成这个HTML(网络服务器)还是只是想用命令行或Windows可执行文件周期性地/周期性地生成这个文件?另外,您是否需要在现有文档中“替换”它们,还是可以重新生成整个文档? – 2011-06-07 23:23:28

回答

1

啜你的HTML到XmlDocument(您的标记是有效的,不是吗?),然后使用XPath找到具有href属性的所有<a>标签。应用变换并将新值分配给href属性。然后写出XmlDocument。

简单!

0

使用正则表达式查找值和替换 像"/<p><a herf=\"[^\"]+\">([^<]+)<\\/a><\\/p>一个正则表达式匹配和捕捉ANCOR文本

+0

我不能只是取代它们,我需要从锚文本中取出33并执行查找并替换url – lordy1981 2011-06-07 22:39:39

+0

您可以使用捕获组捕获ancor文本 – Dani 2011-06-07 22:40:09

+0

考虑到该问题已经有'regex'标记这个答案同它的缺席一样有用。 – Snowbear 2011-06-07 22:41:17

5

尽管这不会回答你的问题,在HTML敏捷性包是操作和工作的好工具与HTML:http://html-agility-pack.net

它至少可以抓住你需要的价值观,并做更换更容易一些。

包含链接使用HTML敏捷性包:How to use HTML Agility pack

+1

我使用了敏捷包,取得了巨大成功。正则表达式的问题是,如果标记不正确,您可能会错过或错过命中。 HTML敏捷性包正是OP所需的。 – SRM 2011-06-07 22:48:24

0

考虑使用以下粗略的算法。

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的指标并没有改变。)

0

所以,你想要做的是根据匹配的内容生成替换字符串。请考虑使用MatchEvaluatorRegex.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而是明确创建一个委托方法。