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

风流意气都作罢 提交于 2021-01-28 11:15:24

问题


Referencing the help file for `Invoke-RestMethod:

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                   
 

How can I convert the response to xml and output it, as above, in a single line?


回答1:


The specific URI you're targeting returns XML content, which Invoke-RestMethod automatically parses into XML DOMs of type System.Xml.XmlElement (an array of such instances in this case).

A simple way to visualize the output is to access the .OuterXml property:

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

If you really need a single-line representation:

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



回答2:


Just a slight variant:

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'

which, despite a specified "ContentType" certainly seems to not be XML at least as printed to the console. Still, interesting.



来源:https://stackoverflow.com/questions/64885215/how-to-convert-a-response-from-invoke-restmethod-to-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!