我有一塊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