PowerShell直接转换Invoke-RestMethod返回XML报错问题排查
PowerShell解析XML接口响应的问题
我有一个示例XML文件test.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?> <Response> <Update> <foo>1.1.1</foo> <bar>12345</bar> </Update> </Response>
我尝试用PowerShell获取foo的值,将响应保存到文件再读取的方式可行:
Invoke-RestMethod $myurl | Out-File test.xml [xml]$abc = (Get-Content test.xml) $abc.Response.Update.foo
但以下操作出现问题:
1. 直接将Invoke-RestMethod结果转换为[xml]时报错
执行代码:
[xml]$abc = (Invoke-RestMethod $myurl)
错误信息:
MetadataError: Cannot convert value "<?xml version="1.0" encoding="utf-8"?> <Response> <Update> [...snip...] </Update> </Response>" to type "System.Xml.XmlDocument". Error: "The specified node cannot be inserted as the valid child of this node, because the specified node is the wrong type."
2. 直接赋值Invoke-RestMethod结果后访问节点无输出
执行代码:
$abc = Invoke-RestMethod $myurl $abc.Response $abc.Response.Update $abc.Response.Update.foo
以上代码无任何输出,也不报错。
3. 使用Invoke-WebRequest仍报错,疑似编码问题
执行代码:
[xml]$abc = Invoke-WebRequest $myurl
错误信息中内容开头出现三个问号,报错如下:
MetadataError: Cannot convert value "???<?xml version="1.0" encoding="utf-8"?> <Response> <Update> [...snip...] </Update> </Response>" to type "System.Xml.XmlDocument". Error: "The specified node cannot be inserted as the valid child of this node, because the specified node is the wrong type."
请问我哪里操作出错了?
内容的提问来源于stack exchange,提问作者bahrep
相关产品推荐
相关产品推荐

