我需要将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("<", "<") '< less than
_dictonary.Add(">", ">") '> greater than
_dictonary.Add("&", "&") '& ampersand
_dictonary.Add("¢", "¢") '¢ cent
_dictonary.Add("£", "£") '£ pound
_dictonary.Add("¥", "¥") '¥ yen
_dictonary.Add("€", "€") '€ euro
_dictonary.Add("©", "©") '© copyright
_dictonary.Add("®", "®") '® registered trademark
_dictonary.Add("‘", "‘") ' single quote
_dictonary.Add("’", "’") ' single quote
_dictonary.Add("“", "“") ' Double quote
_dictonary.Add("”", "”") ' Double quote
_dictonary.Add("•", "•") ' Bullet
_dictonary.Add("ç", "Ç")
_dictonary.Add("ë", "Ç")
_dictonary.Add("é", "é")
_dictonary.Add("—", "—")
_dictonary.Add("è", "È")
_dictonary.Add("á", "á")
_dictonary.Add("–", "–")
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 "">
]><a href = 'blah'> < &</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
您可以跳过lt
、gt
和amp
——这些都是有效的XML实体。或者,您可以将该列表重构到您的字典中。