ConvertTo Xml - PowerShell


Overview

ConvertTo-Xml converts an object or collection of objects into XML format. This command is useful for creating XML documents from PowerShell objects, enabling you to store and exchange data in a structured format.

Syntax

ConvertTo-Xml [-InputObject] <object> [-Encoding] <string> [-Depth] <int> [-Stream] {Default | Memory | File} [-Path] <string> [-Append] [-NoIndent] [-Namespace] <string> [-Type] <string> [-Fragment] [-Delimiter] <string>

Options/Flags

| Parameter | Description | Default |
|—|—|—|
| -InputObject | Specifies the object or collection of objects to convert to XML. | N/A |
| -Encoding | Sets the encoding for the XML output. | UTF8 |
| -Depth | Specifies the maximum depth of nested objects to convert. 0 converts all nested objects. | 0 |
| -Stream | Specifies where to output the XML. Default streams to console, Memory stores in memory object, File outputs to specified file. | Default |
| -Path | Specifies the path to the output XML file when using -Stream File. | N/A |
| -Append | Appends to the output XML file instead of overwriting if it exists. | False |
| -NoIndent | Prevents indenting in the XML output for a more compact format. | False |
| -Namespace | Specifies the XML namespace URI to use. | urn:schemas-microsoft-com:powershell |
| -Type | Specifies the XML element type name for the output. | Object |
| -Fragment | Creates a fragment of XML rather than a complete document. | False |
| -Delimiter | Specifies the delimiter to use for joining values of array-type objects. | , |

Examples

Simple Object Conversion:

$student = New-Object -TypeName PSObject -Property @{
  Name = "John Doe";
  Age = 25;
  Grade = "A"
}

$xml = ConvertTo-Xml -InputObject $student

Output:

<Object xmlns="urn:schemas-microsoft-com:powershell">
  <Name>John Doe</Name>
  <Age>25</Age>
  <Grade>A</Grade>
</Object>

Array Object Conversion with Delimiter:

$numbers = 1, 2, 3, 4, 5

$xml = ConvertTo-Xml -InputObject $numbers -Delimiter '|'

Output:

<Object xmlns="urn:schemas-microsoft-com:powershell" Type="System.Int32[]">1|2|3|4|5</Object>

Common Issues

  • Invalid XML: Ensure that the input object can be validly represented as XML.
  • File Write Errors: Check write permissions and ensure the specified path exists.
  • Namespace Conflicts: If the -Namespace URI is already in use, the XML may be invalid.

Integration

Combine with PowerShell to Flatten JSON:

$json = (Get-Content .\data.json) | ConvertFrom-Json
$xml = ConvertTo-Xml -InputObject $json -Depth 1 -Namespace ''

Pipe Output to a RESTful Endpoint:

$xml = ConvertTo-Xml -InputObject $customerData
Invoke-WebRequest -Method Post `
  -Uri 'https://api.example.com/customers' `
  -Body $xml
  • Export-Clixml
  • Import-Clixml
  • ConvertFrom-Xml