为什么XmlDocument.LoadXml抛出System.Net.WebException?

时间:2011-09-12 13:49:09

标签: .net xml vb.net exception-handling xmldocument

为什么System.Xml.XmlDocument.LoadXml方法抛出System.Net.WebException

这真是令人难以置信的疯狂,如果MSDN是正确的,LoadXml最多只能给我一个System.Xml.XmlException

然而,我有奇怪的例外,如:

  

基础连接已关闭:连接意外关闭。

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)

究竟是什么造成了例外?

2 个答案:

答案 0 :(得分:8)

XmlDocument的内部XmlReader使用XmlResolver加载外部资源。您应该通过将XmlResolver设置为null并将DtdProcessing设置为忽略来阻止打开DTD。这可以通过将XmlReaderSettings对象应用于新XmlReader来完成。然后可以使用此阅读器将XML加载到XmlDocument中。这应该可以解决你的问题。

    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

答案 1 :(得分:4)

Edwin给了你解决方案,我告诉你连接丢失的原因:

http://www.w3.org/blog/systeam/2008/02/08/w3c_s_excessive_dtd_traffic/

相关问题