xmlpowershellrestread-eval-print-loopinvoke-restmethod

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


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?


Solution

  • The specific URI you're targeting returns XML content, which Invoke-RestMethod automatically parses into XML DOMs (document object models) 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'
    

    You can work with these XmlElement instances using OOP techniques, relying on PowerShell's convenient adaptation of the XML DOM; for instance, the following extracts the value of the <title> child element from all array elements, using member-access enumeration:

    $entries = Invoke-RestMethod -Uri https://blogs.msdn.microsoft.com/powershell/feed/
    $entries.title
    

    Note: