Why does System.Xml.XmlDocument.LoadXml
method 开发者_开发知识库throw System.Net.WebException
?
This is really mind boggling crazy, if MSDN was right, LoadXml
should at most give me a System.Xml.XmlException
.
Yet I have weird exceptions like:
The underlying connection was closed: The connection was closed unexpectedly.
Dim document As New XmlDocument
document.LoadXml("<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd""><x></x>")
MsgBox(document.LastChild.Name)
What on earth is causing the exception ?
The internal XmlReader of a XmlDocument uses a XmlResolver to load external resources. You should prevent the opening of the DTD by setting the XmlResolver
to null and setting DtdProcessing
to ignore. This can be done by applying a XmlReaderSettings
object to a new XmlReader
. This reader can then be used to load the XML into the XmlDocument. That should solve your issue.
Dim doc As New XmlDocument()
Dim settings As New XmlReaderSettings()
settings.XmlResolver = Nothing
settings.DtdProcessing = DtdProcessing.Ignore
Using sr As New StringReader("<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd""><x></x>")
Using reader As XmlReader = XmlReader.Create(sr, settings)
doc.Load(reader)
End Using
End Using
Edwin gave you the solution, and I'm giving you the reason for the connection drop:
http://www.w3.org/blog/systeam/2008/02/08/w3c_s_excessive_dtd_traffic/
精彩评论