J. *_* Ed 4 html c# regex parsing html-parsing
我将从最后开始:
在我的C#程序中,我有一个包含HTML的字符串,我想从这个字符串中的元素中删除所有内联样式属性(style=".."
),以及所有以'abc'开头的类.
我愿意为此使用正则表达式,即使有些人喋喋不休 :).
(一个解释,对于那些希望指责我解析HTML字符串的人:
我被迫对我的项目使用一些不太理想的Web控件.控件被设计为在服务器端使用(即使用回发和所有这些)东西),但我需要在ajax调用中使用它.
这意味着我必须在代码中配置它,调用它的Render()
方法,它给我HTML字符串,并将该字符串传递给客户端,在那里插入在适当的地方使用DOM.不幸的是,我无法找到控件的正确配置来阻止它使用这些无用的样式和类来呈现自己,所以我不得不手动删除它们.请不要恨我.)
试试这个:
string html;
string cleaned = new Regex("style=\"[^\"]*\"").Replace(html, "");
string cleaned = new Regex("(?<=class=\")([^\"]*)\\babc\\w*\\b([^\"]*)(?=\")").Replace(cleaned, "$1$2");
Run Code Online (Sandbox Code Playgroud)
对任何有兴趣的人 - 我已经解决了这个问题而没有使用RegEx;
相反,我曾经XDocument
解析过html-
private string MakeHtmlGood(string html)
{
var xmlDoc = XDocument.Parse(html);
// Remove all inline styles
xmlDoc.Descendants().Attributes("style").Remove();
// Remove all classes inserted by 3rd party, without removing our own lovely classes
foreach (var node in xmlDoc.Descendants())
{
var classAttribute = node.Attributes("class").SingleOrDefault();
if (classAttribute == null)
{
continue;
}
var classesThatShouldStay = classAttribute.Value.Split(' ').Where(className => !className.StartsWith("abc"));
classAttribute.SetValue(string.Join(" ", classesThatShouldStay));
}
return xmlDoc.ToString();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7308 次 |
最近记录: |