Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 577
Pacerier Avatar asked Sep 12 '11 13:09

Pacerier


1 Answers

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
like image 127
Edwin de Koning Avatar answered Oct 05 '22 10:10

Edwin de Koning