从Web地址加载xml文件时出现异常

时间:2014-03-21 09:06:10

标签: xml exception powershell powershell-v2.0

我正在尝试在PowerShell中加载xml文件。以下是我的代码段

$url= "http://mYjenkins:8081/job/Test/config.xml"
$doc = New-Object System.Xml.XmlDocument
$doc.Load($url) 

但是这段代码总是返回错误

Exception calling "Load" with "1" argument(s): "The server committed a protocol violation. Section=ResponseStatusLine"
At line:1 char:10
+ $doc.Load($url)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

我也使用了下面的代码,

[xml]$doc = (New-Object System.Net.WebClient).DownloadString($url)

但是这也会返回相同的错误。请提出一些解决方案来解决这个问题

1 个答案:

答案 0 :(得分:1)

不是将文件直接加载到XML文档中,而是将其加载到变量中以进行进一步分析。没有任何代理和身份验证,它就像这样非常简单,

$wc = New-Object Net.WebClient 
$s = $wc.DownloadString("http://what.ever/doc.xml")

使用集成的Windows身份验证,传递默认凭据,如此,

$wc = New-Object Net.WebClient 
$wc.Credentials = [Net.CredentialCache]::DefaultCredentials
$s = $wc.DownloadString("http://what.ever/doc.xml")

对于需要身份验证的代理,事情稍微复杂一些,

$proxy = [Net.WebRequest]::GetSystemWebProxy()
$proxy.Credentials = [Net.CredentialCache]::DefaultCredentials

$wc = New-Object Net.WebClient
$wc.UseDefaultCredentials = $true  
$wc.Proxy.Credentials = $wc.Credentials
$s = $wc.DownloadString("http://what.ever/doc.xml")

既然您已经在变量中获得了XML文档,那么检查实际情况应该很容易。