C#:替换全部的正则表达式<;字体>;HTML中的标记由<;span>;
我想用替换HTML文件中的所有标记,并保留字体颜色和字体大小等属性 以下是测试用例:C#:替换全部的正则表达式<;字体>;HTML中的标记由<;span>;,c#,regex,C#,Regex,我想用替换HTML文件中的所有标记,并保留字体颜色和字体大小等属性 以下是测试用例: 案例1 案例2 案例3 正如@Steve B评论的那样 不要使用正则表达式。HTML有太多的方法来编写标记,以至于你会以一个可怕的正则表达式结束。我的建议是使用HtmlAgilityPack,它允许您解析和操作HTML。当处理HTML操作时,这个库是一个黄金纽结。它是免费的,开源的 在这里,您可以使用HtmlAgilityPack public string ReplaceFontBySpan() {
案例1
案例2
案例3
正如@Steve B评论的那样
不要使用正则表达式。HTML有太多的方法来编写标记,以至于你会以一个可怕的正则表达式结束。我的建议是使用HtmlAgilityPack,它允许您解析和操作HTML。当处理HTML操作时,这个库是一个黄金纽结。它是免费的,开源的 在这里,您可以使用HtmlAgilityPack
public string ReplaceFontBySpan()
{
HtmlDocument doc = new HtmlDocument();
string htmlContent = @"<font color='#000000'>Case 1</font><br />
<font size=6>Case 2</font><br />
<font color='red' size='12'>Case 3</font>";
doc.LoadHtml(htmlContent);
foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//font"))
{
var attributes = node.Attributes;
foreach (var item in attributes)
{
if (item.Name.Equals("size"))
{
item.Name = "font-size";
item.Value = item.Value + "rem";
}
}
var attributeValueList = node.Attributes.Select(x => x.Name + ":" + x.Value).ToList();
string attributeName = "style";
string attributeValue = string.Join(";", attributeValueList);
HtmlNode span = doc.CreateElement("span");
span.Attributes.Add(attributeName, attributeValue);
span.InnerHtml = node.InnerHtml;
node.ParentNode.ReplaceChild(span, node);
}
return doc.DocumentNode.OuterHtml;
}
公共字符串ReplaceFontBySpan()
{
HtmlDocument doc=新的HtmlDocument();
字符串htmlContent=@“案例1
案例2
案例3”;
doc.LoadHtml(htmlContent);
foreach(doc.DocumentNode.SelectNodes(“//字体”)中的HtmlNode节点)
{
var attributes=node.attributes;
foreach(属性中的变量项)
{
如果(item.Name.Equals(“size”))
{
item.Name=“font size”;
item.Value=item.Value+“rem”;
}
}
var attributeValueList=node.Attributes.Select(x=>x.Name+”:“+x.Value.ToList();
字符串attributeName=“style”;
string attributeValue=string.Join(“;”,attributeValue列表);
HtmlNode span=doc.CreateElement(“span”);
Add(attributeName,attributeValue);
span.InnerHtml=node.InnerHtml;
node.ParentNode.ReplaceChild(跨度,节点);
}
返回doc.DocumentNode.OuterHtml;
}
输出:
使用regex解析/更改HTML=EVIL。。。不要使用正则表达式。HTML有太多的方法来编写标记,以至于你会以一个可怕的正则表达式结束。我的建议是使用它来解析和操作HTML。当处理HTML操作时,这个库是一个黄金纽结。而且它是免费的,开源的。可能是Html Agility Pack的副本。你已经得到了一个很好的答案。也许这可能是“如何在C#中使用正则表达式解析HTML”的新标准答案——不错的答案——有时“如何做到这一点”的最佳答案是“不要那样做,做其他事情”@Ben,谢谢,-是的,有时是最好的:)