Skip to main content
 首页 » 编程设计

c#之使用正则表达式 C# 将属性插入 HTML 元素

2024年01月22日23sharpest

string htmlHeaderPattern = ("(<h[2|3])>.*</h[2|3]>)"); 
MatchCollection matches = Regex.Matches(mainBody, htmlHeaderPattern, RegexOptions.Compiled); 

从这段代码中,我得到了一堆 h2 和 h3 元素。在这些中,我想插入一个 ID 属性,其值等于(标题中的内容,减去特殊字符和 ToLower())。我还需要将此值作为单独的字符串,因为我需要存储它供以后使用。

  • 输入:<h3>Some sort of header!</h3>
  • 输出:<h3 id="#some-sort-of-header">Some sort of header!</h3>
  • 另外,我需要值“#some-sort-of-header”和“Some sort of header!”存储在字典或列表或其他任何东西中。

这是我目前所拥有的:

string htmlHeaderPattern = ("(<h[2|3]>.*</h[2|3]>)"); 
MatchCollection matches = Regex.Matches(mainBody, htmlHeaderPattern, RegexOptions.Compiled); 
Dictionary<string,string> returnValue = new Dictionary<string, string>(); 
 
foreach (Match match in matches) 
{ 
 
    string idValue = StripTextValue(match.Groups[4].Value); 
     returnValue.Add(idValue, match.Groups[4].Value); 
} 
MainBody = Regex.Replace(mainBody, htmlHeaderPattern, "this is where i must replace all the headers with one with an ID-attribute?"); 

有没有正则表达式向导可以帮助我?

请您参考如下方法:

有很多关于在解析 HTML 时不要使用正则表达式的提及,因此您可以使用例如Html Agility Pack为此:

var html = @"<h2>Some sort of header!</h2>"; 
 
HtmlDocument document= new HtmlDocument(); 
document.LoadHtml(html); 
 
var headers = document.DocumentNode.SelectNodes("//h2|//h3"); 
if (headers != null) 
{ 
    foreach (HtmlNode header in headers) 
    { 
        var innerText = header.InnerText; 
        var idValue = StripTextValue(innerText); 
        if (header.Attributes["id"] != null) 
        { 
            header.Attributes["id"].Value = idValue; 
        } 
        else 
        { 
            header.Attributes.Add("id", idValue); 
        } 
    } 
} 

此代码找到所有 <h2>和 <h3>传递文档中的元素,从那里获取内部文本并设置(或添加)id它们的属性。

在这个例子中你应该得到类似的东西:

<h2 id='#some-sort-of-header'>Some sort of header!</h2>