HTML使用LINQ解码字符串数组
本文关键字:字符串 数组 解码 LINQ 使用 HTML | 更新日期: 2023-09-27 17:59:54
如何使用LINQ
解码string[]
?
例如。我从string[]
而不是Institute's
获得string
作为Institute's
我试过了,
values.ForEach(item => WebUtility.HtmlDecode(item));
其中values
是我的string[]
。。
但我还是没能得到想要的结果。
编辑:
如上所示,我的原始字符串是Institution's
,我将其作为编码的
Institute's
-->一级编码
Institute's
-->二级编码
在应用以下解决方案后,我能够获得解码结果的第一级编码以上作为
Institute's
但无法获得实际字符串Institute's
您没有看到任何更改的原因是WebUtility.HtmlDecode
没有为您传递的参数赋值,而是返回html解码值。
String encodedString = "&";
//this does nothing
WebUtility.HtmlDecode(encodedString);
//this assigns the decoded value to a new string
String decodedString = WebUtility.HtmlDecode(encodedString);
这也是为什么(正如Henrik提到的)应该在linq查询中使用Select
的原因。
你会这样使用它:
values = values.Select(item => WebUtility.HtmlDecode(item));
这段代码对我有用:
string[] values = new string[] {
"Institute's",
"Institute's",
"Institute's",
"Institute's",
"Institute's"};
List<string> decoded = new List<string>();
Regex encDet = new Regex(@"'&.+;", RegexOptions.Compiled|RegexOptions.IgnoreCase);
values.ToList().ForEach(item => {
string decodedItem = item;
while(encDet.IsMatch(decodedItem)){
decodedItem = WebUtility.HtmlDecode(decodedItem);
}
decoded.Add(decodedItem);
});
values = decoded.ToArray();
编辑:
如果您只需要"纯"LINQ来解码双重编码的字符串,下面是另一行代码片段:
values = values.Select(item => WebUtility.HtmlDecode(WebUtility.HtmlDecode(item))).ToArray();
干杯!
var decodedValues = HtmlDoubleDecode(values);
其中HtmlDoubleDecode是:
public string[] HtmlDoubleDecode(string[] values)
{
return values
.Select (v => WebUtility.HtmlDecode(WebUtility.HtmlDecode(v)))
.ToArray();
}