.NET xElement错误协调(html实体名称到其数字字符引用的转换)



我需要将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

这里会遇到很多问题。尽管您想捕获无效的HTML,但也有有效的HTML是无效的XML——例如,<br>是有效的HTML,而不是无效的XML。

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

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

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

  • http://www.w3.org/TR/xhtml1/DTD/xhtml-lat1.ent
  • http://www.w3.org/TR/xhtml1/DTD/xhtml-special.ent
  • http://www.w3.org/TR/xhtml1/DTD/xhtml-symbol.ent

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

最新更新