PowerShell – Convert XML to String
In PowerShell, you can convert an XML object to a string using the OuterXml
property of the XML object. This property returns the XML representation of the object as a string.
Example:
$xml = @"
<bookstore>
<book genre="novel" publicationdate="2021-01-01" ISBN="123456789">
<title>Sample Book</title>
<author>John Doe</author>
<price>19.99</price>
</book>
</bookstore>
"@
# Load the XML string
[xml]$xmlObject = $xml
# Convert the XML object to a string
$xmlString = $xmlObject.OuterXml
# Output the result
$xmlString
In the above example, we have an XML string containing book information. By using the [xml]
type accelerator, we load the string as an XML object. Then we access the OuterXml
property of the object, which returns the XML representation of the object as a string. Finally, we assign the result to the variable $xmlString
and output it.
The output will be:
<book genre="novel" publicationdate="2021-01-01" ISBN="123456789">
<title>Sample Book</title>
<author>John Doe</author>
<price>19.99</price>
</book>
As you can see, the $xmlString
variable now contains the XML content as a string.