【问题标题】:.NET xElement error reconciliation (html entity name to its numeric character reference conversion).NET xElement 错误协调(html 实体名称到其数字字符引用的转换)
【发布时间】:2015-04-28 13:16:51
【问题描述】:

我需要将 HTML 解析为 xElement。我知道这个解决方案对于格式错误的 HTML 不是很宽容。这很好,因为无论如何我都想陷入无效的 HTML。但是,我不希望 XElement.Parse() 方法在遇到 HTML 实体时失败。

我想知道 .NET 框架中是否内置了一些东西,可以将命名的 HTML 实体转换为数字字符引用。

这行得通,但我真的不想对每个实体都这样做。

Public Function GetEntityReplacementList() As IDictionary(Of String, String)
    'http://www.w3.org/TR/html4/sgml/entities.html
    Dim _dictonary As New Dictionary(Of String, String)
    _dictonary.Add(" ", " ") ' " " non-breaking space
    _dictonary.Add("&lt;", "&#60;") '<  less than
    _dictonary.Add("&gt;", "&#62;") '>  greater than
    _dictonary.Add("&amp;", "&#38;") '&     ampersand
    _dictonary.Add("&cent;", "&#162;") '¢   cent
    _dictonary.Add("&pound;", "&#163;") '£  pound
    _dictonary.Add("&yen;", "&#165;") '¥    yen
    _dictonary.Add("&euro;", "&#8364;") '€  euro
    _dictonary.Add("&copy;", "&#169;") '©   copyright
    _dictonary.Add("&reg;", "&#174;") '® registered trademark
    _dictonary.Add("&lsquo;", "&#8216;") ' single quote
    _dictonary.Add("&rsquo;", "&#8217;") ' single quote
    _dictonary.Add("&ldquo;", "&#8220;") ' Double quote
    _dictonary.Add("&rdquo;", "&#8221;") ' Double quote
    _dictonary.Add("&bull;", "&#8226;") ' Bullet
    _dictonary.Add("&ccedil;", "&#199;")
    _dictonary.Add("&euml;", "&#199;")
    _dictonary.Add("&eacute;", "&#233;")
    _dictonary.Add("&mdash;", "&#8212;")
    _dictonary.Add("&egrave;", "&#200;")
    _dictonary.Add("&aacute;", "&#225;")
    _dictonary.Add("&ndash;", "&#8211;")
    Return _dictonary
End Function

<Extension()>
Public Function CreateXElementWithEntityReplacements(p_xml As String) As XElement


    For Each _pair In GetEntityReplacementList()
        p_xml = Regex.Replace(p_xml, _pair.Key, _pair.Value, RegexOptions.IgnoreCase)
    Next

    Return XElement.Parse(p_xml)

End Function

【问题讨论】:

  • 您是否考虑过改用 HtmlAgilitypack?
  • 我有,我暂时避免使用第三方库。
  • 有人吗?我在 MSDN 中没有找到任何内容。

标签: html .net xml


【解决方案1】:

你会在这里遇到很多问题。尽管您想捕获无效的 HTML,但存在无效的 XML 的有效 HTML - 例如,&lt;br&gt; 是有效的 HTML 但无效的 XML。

但是,如果您确信您的解决方案需要解析也是有效 XML 的 HTML,您只需将正确的实体定义添加到文档字符串的顶部,它就会解析正确地从那里出来。例如,您可以将以下内容添加到您的 html 字符串中:

<!DOCTYPE documentElement[
  <!ENTITY nbsp "&#16;">
]><a href = 'blah'>&nbsp; &lt; &amp;</a>

这将被解析为有效的 HTML。您可以从 HTML DTD 中获取实体列表,可在此处获得:

您可以跳过 ltgtamp - 这些都是有效的 XML 实体。或者,您可以将该列表重构到您的字典中。

【讨论】:

  • 感谢您的反馈。你完全正确。我正在写一个 Epub 阅读器,所以我还必须考虑格式错误的 html。我不认为 xElement 类是要走的路了。
  • 我知道您说过要避免使用第三方库,但这几乎正是 HtmlAgilityPack 的用途。 htmlagilitypack.codeplex.com
猜你喜欢
  • 1970-01-01
  • 2011-03-09
  • 2020-05-09
  • 2016-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-02
  • 1970-01-01
相关资源
最近更新 更多