Recently, I was working on some code (of course) and had a need to convert some XML to PowerShell PSObjects. I found some snippets out there that sort of did this, but not the way that I needed for this exercise. In this case I’m converting XML meta data from Plex.
function ConvertFrom-XmlPart($xml) { $hash = @{} $xml | Get-Member -MemberType Property | ` % { $name = $_.Name if ($_.Definition.StartsWith("string ")) { $hash.($Name) = $xml.$($Name) } elseif ($_.Definition.StartsWith("System.Object[] ")) { $obj = $xml.$($Name) $hash.($Name) = $($obj | %{ $_.tag }) -join "; " } elseif ($_.Definition.StartsWith("System.Xml")) { $obj = $xml.$($Name) $hash.($Name) = @{} if ($obj.HasAttributes) { $attrName = $obj.Attributes | Select-Object -First 1 | % { $_.Name } if ($attrName -eq "tag") { $hash.($Name) = $($obj | % { $_.tag }) -join "; " } else { $hash.($Name) = ConvertFrom-XmlPart $obj } } if ($obj.HasChildNodes) { $obj.ChildNodes | % { $hash.($Name).($_.Name) = ConvertFrom-XmlPart $($obj.$($_.Name)) } } } } return $hash } function ConvertFrom-Xml($xml) { $hash = @{} $hash = ConvertFrom-XmlPart($xml) return New-Object PSObject -Property $hash }