2011-06-07 92 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而是明確創建一個委託方法。