Skip to content

Instantly share code, notes, and snippets.

@mkol5222
Forked from elvarb/ConvertFrom-Xml.ps1
Created November 29, 2021 08:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkol5222/017f2254308782eadeda4be44f932588 to your computer and use it in GitHub Desktop.
Save mkol5222/017f2254308782eadeda4be44f932588 to your computer and use it in GitHub Desktop.
Powershell to convert XML to JSON
# From https://stackoverflow.com/questions/42636510/convert-multiple-xmls-to-json-list
# Use
# [xml]$var = Get-Content file.xml
# Convert to JSON with
# $var | ConvertFrom-XML | ConvertTo-JSON -Depth 3
# Helper function that converts a *simple* XML document to a nested hashtable
# with ordered keys.
function ConvertFrom-Xml {
param([parameter(Mandatory, ValueFromPipeline)] [System.Xml.XmlNode] $node)
process {
if ($node.DocumentElement) { $node = $node.DocumentElement }
$oht = [ordered] @{}
$name = $node.Name
if ($node.FirstChild -is [system.xml.xmltext]) {
$oht.$name = $node.FirstChild.InnerText
} else {
$oht.$name = New-Object System.Collections.ArrayList
foreach ($child in $node.ChildNodes) {
$null = $oht.$name.Add((ConvertFrom-Xml $child))
}
}
$oht
}
}
[xml[]] (Get-Content -Raw file[12].xml) | ConvertFrom-Xml | ConvertTo-Json -Depth 3
# -Depth might need tweaking depending on the depth of the XML file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment