我有一些HTML内容,我想在我的网页上显示之前解析和编码。
诀窍是我想只编码文本内容,而不是HTML内容中明显的HTML标签。我怎样才能做到这一点?
例:
提供
"Some text & links : <strong>bla blà blö</strong> and <a href="http://www.google.com">go there</a> for only 15 € < 20 €"
我想输出
"Some text & links : <strong>bla blà blö</strong> and <a href="http://www.google.com">go there</a> for only 15 € < 20 €"
or
"Some text & links : <strong>bla blà blö</strong> and <a href="http://www.google.com">go there</a> for only 15 € < 20 €"
var html =
"Some text & links : <strong>bla blà blö</strong> and <a href=\"http://www.google.com\">go there</a> for only 15 € < 20 €";
// This
HtmlAgilityPack.HtmlEntity.Entitize(html);
// Outputs
Some text & links : <strong>bla blà blö</strong> and <a href="http://www.google.com">go there</a> for only 15 € < 20 €
刚刚测试过,它在你的例子中效果很好。
如果你想看看它是如何完成的,那就是public。
我知道这是一个老话题,但我认为这个片段可能做得很好。我也知道你不应该将RegEx用于HTML标签(因为它根本没有解决<script>
和<style>
),但是这个方法可能是你需要的而不是获得整个HTMLAgilityPack ....我使用SqlString因为这个我的SQL Server数据库使用该方法。可以轻松切换到字符串。也很容易更改为StringBuilder以使其更加优化。
private static SqlString fnHTMLDecodeEncode(SqlString html, bool encode)
{
if (html.IsNull)
return SqlString.Null;
const RegexOptions REGOPT = RegexOptions.Singleline | RegexOptions.Compiled;
string s = html.Value;
var m = Regex.Matches(s, @"(<[!A-Za-z\/][^>]*>", RegexOptions.Singleline | RegexOptions.Compiled);
int proStart, proLen;
if (m.Count == 0)
{
proStart = 0;
proLen = s.Length;
}
else
{
proStart = m[m.Count - 1].Index + m[m.Count - 1].Length;
proLen = s.Length - proStart;
}
for (int i = m.Count; i >= 0; i--)
{
if (i < m.Count)
{
proStart = (i == 0 ? 0 : m[i - 1].Index + m[i - 1].Length);
proLen = m[i].Index - proStart;
}
if (proLen > 2)
{
var orig = s.Substring(proStart, proLen);
var enc = (encode ? System.Net.WebUtility.HtmlEncode(orig) : System.Net.WebUtility.HtmlDecode(orig));
if (orig.Length != enc.Length)
{
s = s.Remove(proStart, proLen).Insert(proStart, enc);
}
proLen = -1;
}
}
return new SqlString(s);
}