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

时间:2015-04-28 13:16:51

标签: html .net xml

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

我想知道.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

0 个答案:

没有答案