PowerShell: How to Convert XML to String


Often you may want to use PowerShell to convert an XML object to a string.

You can use the following methods to do so:

Method 1: Use OuterXml

[xml]$my_xml = Get-Content my_data.xml

$my_xml.OuterXml

This particular example will convert the XML object named $my_xml to a string.

Method 2: Use OuterXml and PreserveWhiteSpace

$my_xml = [xml]::new()
$my_xml.PreserveWhitespace = $true
$my_xml.Load('my_data.xml')

$my_xml.OuterXml

This particular example will output the XML object named $my_xml to a string while preserving the whitespace of the formatting.

The following examples show how to use each method in practice.

Example 1: Use OuterXml to Convert XML to String 

Suppose that we have an XML file named my_data.xml in our current directory.

We can use the Get-Content cmdlet to view the contents of this file:

We can use the following syntax to load this XML file into an object named $my_xml and then convert the object to a string:

[xml]$my_xml = Get-Content my_data.xml

$my_xml.OuterXml

The following screenshot shows how to use this syntax in practice:

PowerShell convert XML object to string

Notice that the output displays the XML object as a string.

Example 2: Use OuterXml and PreserveWhiteSpace to Convert XML to String 

Once again, suppose that we have an XML file named my_data.xml in our current directory:

We can use the following syntax to load this XML file into an object named $my_xml and then convert the object to a string, while preserving the whitespace in the formatting of the file:

$my_xml = [xml]::new()
$my_xml.PreserveWhitespace = $true
$my_xml.Load('my_data.xml')

$my_xml.OuterXml

The following screenshot shows how to use this syntax in practice:

PowerShell convert XML to string and preserve whitespace

The output displays the XML object as a string.

Notice that the whitespace in the formatting of the file has been preserved.

Note: You can find the complete documentation for the PreserveWhiteSpace property in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Update Content in XML File
PowerShell: How to Edit a JSON File
PowerShell: How to Loop Through Each Line of CSV File

Leave a Reply