将字符实体转换为其unicode等效项

我在数据库中有html编码的字符串,但许多字符实体不仅仅是标准的&< 。 实体喜欢 。 不幸的是,我们需要将这些数据提供给基于闪存的rss阅读器,而flash不会读取这些实体,但它们会读取等效的unicode(ex )。

使用.Net 4.0,是否有任何实用方法可以将html编码的字符串转换为使用unicode编码的字符实体?

这是我需要的更好的例子。 db有html字符串,如:

John & Sarah went to see $ldquo;Scream 4$rdquo;.

John & Sarah went to see $ldquo;Scream 4$rdquo;.

我需要在rss / xml文档中输出标签: <p>John & Sarah went to see “Scream 4”.</p> <p>John & Sarah went to see “Scream 4”.</p>

我正在使用XmlTextWriter从数据库记录创建xml文档,类似于此示例代码http://www.dotnettutorials.com/tutorials/advanced/rss-feed-asp-net-csharp.aspx

所以我需要将数据库中的html字符串中的所有字符实体替换为其unicode等效,因为基于闪存的rss阅读器无法识别超出最常见的任何实体,例如&

我的第一个想法是,您的RSS阅读器能否接受实际角色? 如果是这样,您可以使用HtmlDecode并直接输入。

如果你确实需要将它转换为数字表示,你可以解析每个实体, HtmlDecode它,然后将它转换为int以获得base-10 unicode值。 然后将其重新插入字符串中。

编辑:这里有一些代码来certificate我的意思(它是未经测试的,但得到的想法):

 string input = "Something with — or other character entities."; StringBuilder output = new StringBuilder(input.Length); for (int i = 0; i < input.Length; i++) { if (input[i] == '&') { int startOfEntity = i; // just for easier reading int endOfEntity = input.IndexOf(';', startOfEntity); string entity = input.Substring(startOfEntity, endOfEntity - startOfEntity); int unicodeNumber = (int)(HttpUtility.HtmlDecode(entity)[0]); output.Append("&#" + unicodeNumber + ";"); i = endOfEntity; // continue parsing after the end of the entity } else output.Append(input[i]); } 

我可能在那里的某个地方有一个一个一个错误,但它应该是接近的。

HttpUtility.HtmlDecode会为你工作吗?

我意识到它不会转换为unicode等效实体,而是将其转换为unicode。 是否有特定原因需要unicode等效实体?

更新编辑


  string test = "

John & Sarah went to see “Scream 4”.

"; string decode = HttpUtility.HtmlDecode(test); string encode = HttpUtility.HtmlEncode(decode); StringBuilder builder = new StringBuilder(); foreach (char c in encode) { if ((int)c > 127) { builder.Append("&#"); builder.Append((int)c); builder.Append(";"); } else { builder.Append(c); } } string result = builder.ToString();

您可以从W3C下载相应HTML和/或XHTML DTD的本地副本。 然后设置XmlResolver并使用它来展开文档中找到的任何实体。

您可以使用正则表达式来查找/扩展实体,但这对上下文一无所知(例如,不应扩展CDATA部分中的任何内容)。

这可能有助于您将输入路径放在文本框中

  try { FileInfo n = new FileInfo(textBox1.Text); string initContent = File.ReadAllText(textBox1.Text); int contentLength = initContent.Length; Match m; while ((m = Regex.Match(initContent, "[^a-zA-Z0-9<>/\\s(&#\\d+;)-]")).Value != String.Empty) initContent = initContent.Remove(m.Index, 1).Insert(m.Index, string.Format("&#{0};", (int)m.Value[0])); File.WriteAllText("outputpath", initContent); } catch (System.Exception excep) { MessageBox.Show(excep.Message); } }