一次解码整个HTML实体

问题描述:

我想解码HTML或文本。我 - 附相同result-使用此功能:一次解码整个HTML实体

  • HtmlEntity.DeEntitize
  • HttpUtility.HtmlDecode
  • WebUtility.HtmlDecode

例如,当我喜欢解码Martian's atmosphere,我得到Martian's atmosphere而不是

,当我使用这个代码(EXP),一切都是正确的(字符解码):

TextBox1.Text = "Martian's atmosphere" 
    For i = 0 To 2 
     TextBox1.Text = WebUtility.HtmlDecode(TextBox1.Text) 
     i += 1 
    Next 

问题是我不喜欢使用循环,因为有时我不得不解码完整的HTML页面或长文本。

谢谢。

+0

所以你说你要贯穿HtmlDecode字符串前两次它的完全解码? – Dave

+0

'HttpUtility.HtmlDecode'似乎工作:https://dotnetfiddle.net/CVJUxQ –

+0

是的。我必须更多地运行HtmlDecode。如果一个单词有3个编码实体,我必须运行3次HtmlDecode。 – Tajrib

听起来好像你没有任何方法可以预先知道一个字符串需要被解码多少次,直到你得到你想要的结果,所以你将不得不使用循环或递归得到想要的结果。这里是一个递归函数来做到这一点:

function DecodeUntilUnchanged(string str) 
{ 
    string decoded = WebUtility.HtmlDecode(str); 
    if(decoded == str) 
     return str; 
    return DecodeUntilUnchanged(decoded); 
} 

你会使用这样的:

TextBox1.Text = DecodeUntilUnchanged(TextBox1.Text); 
+0

谢谢@Dave。这正是我想要的。你的代码工作。 但是,我想知道为什么** WebUtility.HtmlDecode **不解码整​​个单词。 – Tajrib

+0

这首先取决于你在哪里获得这些字符串。这听起来像你已经有东西''''作为''''然后转义'&'为'&' – Dave