示例:只保留颜色属性。
鉴于:
<span style="margin-left: 2em;color: #008000;font-size:14px;">some text</span>
输出:
<span style="color: #008000;">some text</span>
This answer was written on the assumption that JavaScript was being used. While this answer is still useful (under that assumption) the language has since been specified as C#. So this answer has become incorrect.
Given the HTML:
<span style="margin-left: 2em;color: #008000;font-size:14px;">some text</span>
The following JavaScript should work (currently untested):
var spans = document.getElementsByTagName('span'),
color;
for (var i=0,len=spans.length;i<len;i++){
color = spans[i].style.color;
spans[i].removeAttribute('style');
spans[i].style.color = color;
}
这是使用 Xml.Linq 的解决方案草图:
XElement Load(string xml)
{
using (var reader = new StringReader(xml))
return XElement.Load(reader);
}
string ProcessStyles(string input)
{
var root = Load(input);
var allElements = root.Descendants();
var styleAttributes = allElements.Select(e => e.Attribute(XName.Get("style"))).Where(a => a != null);
foreach (var styleAttribute in styleAttributes)
{
var value = styleAttribute.Value;
var newValue = ProcessCss(value);
styleAttribute.SetValue(newValue);
}
return root.ToString();
}
string ProcessCss(string value)
{
var cssTokens = value.Split(';').Select(t => t.Trim());
// implement your filtering rules here
var filtered = cssTokens.Where(t => t.StartsWith("color"));
return String.Join(";", filtered);
}
该解决方案假定“样式”属性的某些结构。它不适用于更复杂的 CSS(例如,带有注释)。
另请注意,输入字符串必须是格式良好的 XML 文档。(HTML5 通常不必是格式良好的 XML)。
如果您确实想使用正则表达式来完成这项工作,这里有一些代码片段;但我仍然建议你用style
object 来处理这个问题。
搜索style=\"[^\"]*?([cC]olor:\s#[0-9a-fA-F]{1,6};?)[^\"]*?\"
用。。。来代替style="$1"