Why does XmlDocument.LoadXml throw System.Net.WebException?

放肆的年华 提交于 2019-12-06 19:50:29

问题


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 ?


回答1:


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/




回答2:


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


来源:https://stackoverflow.com/questions/7388949/why-does-xmldocument-loadxml-throw-system-net-webexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!