2013-09-05 77 views
0

我想使用C#和RegEx去除HTML字符串中的所有属性(及其值)。HTML属性剥离器

例如:

<p>This is a text</p><span class="cls" style="background-color: yellow">This is another text</span> 

将成为

<p>This is a text</p><span>This is another text</span> 

另外,我需要删除所有属性,无论是否它们的值用引号括起来。

<p class="cls">Some content</p> 
<p class='cls'>Some content</p> 
<p class=cls>Some content</p> 

应该都会导致

<p>Some content</p> 

我不能用HTMLAgilityPack由于安全方面的原因,所以我需要做到这一点使用正则表达式。

+1

可能重复http://stackoverflow.com/ question/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) –

+1

可能你会在这个网页找到你的答案:http://stackoverflow.com/questions/2994448/regex-strip-html -一个ttributes-except-src – pardeew

+1

'由于安全原因,我无法使用HTMLAgilityPack'你能解释更多关于这个吗? – aloisdg

回答

0

我有一个没有正则表达式的解决方案。我们正在使用SubString()IndexOf()的组合。我不检查任何错误。这只是一个想法。

Working Demo

C#:

private static void Main(string[] args) 
{ 
    string s = @"<p>This is a text</p><span class=""cls"" style=""background-color: yellow"">This is another text</span>"; 

    var list = s.Split(new[] {"<"}, StringSplitOptions.RemoveEmptyEntries); 
    foreach (var item in list) 
     Console.Write(ClearAttributes('<' + item)); 
    Console.ReadLine(); 
} 

private static string ClearAttributes(string source) 
{ 
    int startindex = source.IndexOf('<'); 
    int endindex = source.IndexOf('>'); 
    string tag = source.Substring((startindex + 1), (endindex - startindex - 1)); 
    int spaceindex = tag.IndexOf(' '); 
    if (spaceindex > 0) 
     tag = tag.Substring(0, spaceindex); 
    return String.Concat('<', tag, source.Substring(endindex)); 
} 

输出:

<p>This is a text</p><span>This is another text</span> 
[除XHTML自包含标签的正则表达式匹配开放标签](的