Search code examples
xmlpowershell

How to convert XML to PSObject?


Note: I'm using ConvertTo-XML, and cannot use Export-Clixml.

I create a simple PSObject:

$a = New-Object PSObject -Property @{
    Name='New'
    Server = $null
    Database = $null
    UserName = $null
    Password = $null
}

I then convert it into XML using ConvertTo-XML:

$b = $a | Convertto-XML -NoTypeInformation

The XML looks like this:

<?xml version="1.0"?>
<Objects>
  <Object>
    <Property Name="Password" />
    <Property Name="Name">New</Property>
    <Property Name="Server" />
    <Property Name="UserName" />
    <Property Name="Database" />
  </Object>
</Objects>

I'm having trouble figuring out the dot notation or XPath query to extract the attributes/elements and convert $b back to the original PSObject.


Solution

  • You can do this pretty easily with XPath. Although PowerShell usually makes working with XML pretty simple, in this case I think the format using strictly PowerShell syntax would be pretty gross.

    filter XmlProperty([String]$Property) {
        $_.SelectSingleNode("/Objects/Object/Property[@Name='$Property']").InnerText
    }
    
    $Name = $b | Xmlproperty Name
    $Server = $b | XmlProperty Server
    # etc...
    

    EDIT: To generically do this for an XML document that contains one or more Object elements, you can do something like this:

    function ConvertFrom-Xml($XML) {
        foreach ($Object in @($XML.Objects.Object)) {
            $PSObject = New-Object PSObject
            foreach ($Property in @($Object.Property)) {
                $PSObject | Add-Member NoteProperty $Property.Name $Property.InnerText
            }
            $PSObject
        }
    }
    
    ConvertFrom-Xml $b