如何将 Invoke-RestMethod 的响应转换为 XML?

How to convert a response from Invoke-RestMethod to XML?

正在为 `Invoke-RestMethod 引用 help 文件:

PS /home/nicholas> 
PS /home/nicholas> $response = Invoke-RestMethod -Uri https://blogs.msdn.microsoft.com/powershell/feed/ 
PS /home/nicholas> 
PS /home/nicholas> $json = $response | ConvertTo-Json                                                   
WARNING: Resulting JSON is truncated as serialization has exceeded the set depth of 2.
PS /home/nicholas> 
PS /home/nicholas> $xml = $response | ConvertTo-Xml  
PS /home/nicholas> 
PS /home/nicholas> $xml.OuterXml                   
 

如何将 response 转换为 xml 并像上面一样在一行中输出?

您要定位的特定 URI returns XML 内容,Invoke-RestMethod automatically parses into XML DOMs of type System.Xml.XmlElement数组[=在这种情况下有 25=] 个此类实例)。

可视化输出的一种简单方法是访问 .OuterXml 属性:

(Invoke-RestMethod -Uri https://blogs.msdn.microsoft.com/powershell/feed/).OuterXml

如果你真的需要单行表示:

(Invoke-RestMethod -Uri https://blogs.msdn.microsoft.com/powershell/feed/).OuterXml -replace '\r?\n'

只是一个细微的变体:

PS /home/nicholas> 
PS /home/nicholas> $url="https://blogs.msdn.microsoft.com/powershell/feed/"                            
PS /home/nicholas> 
PS /home/nicholas> Invoke-RestMethod -Method Post -Uri $url -Body $body -ContentType 'application/xml'

尽管指定了“ContentType”,但至少在打印到控制台时似乎肯定不是 XML。还是很有意思。

[xml]$testResult = (Invoke-RestMethod -Uri 'url').OuterXml $testResult.Details.Status

如果 xml 是 3