Skip to content

Instantly share code, notes, and snippets.

@JohnLBevan
Created September 27, 2018 17:46
Show Gist options
  • Select an option

  • Save JohnLBevan/647de2807de17ff1f64a0d23fd445c0a to your computer and use it in GitHub Desktop.

Select an option

Save JohnLBevan/647de2807de17ff1f64a0d23fd445c0a to your computer and use it in GitHub Desktop.
Convert XML to HashTable or JSON
function Convert-XmlToHash {
[CmdletBinding(DefaultParameterSetName = 'XmlDocument')]
Param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'XmlDocument')]
[System.Xml.XmlDocument]$XmlDocument
,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'XmlElement')]
[System.Xml.XmlElement]$InputObject
,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'XmlText')]
[System.Xml.XmlText]$XmlText
,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'XmlAttribute')]
[System.Xml.XmlAttribute]$XmlAttribute
)
Process {
switch ($PSCmdlet.ParameterSetName) {
'XmlDocument' {
$XmlDocument.DocumentElement | Convert-XmlToHash
}
'XmlElement' {
[hashtable]@{
"$($InputObject.Name)" = (@() + $InputObject.Attributes + $InputObject.ChildNodes) | Convert-XmlToHash
}
}
'XmlText' {
$XmlText.Value
}
'XmlAttribute' {
[hashtable]@{
"@$($XmlAttribute.Name)" = $XmlAttribute.Value
}
}
}
}
}
Example #1
{
"root": [
{
"node1": "test"
},
{
"node1": "test2"
},
{
"node1b": "test3"
},
{
"node1c": [
{
"node2": "test4"
},
{
"node2": [
{
"@id": "attrtest"
},
"test5"
]
}
]
}
]
}
Example #2
{
"root": {
"node1": "hello"
}
}
Example #3
{
"root": {
"node1": {
}
}
}
Example #4
{
"root": {
}
}
Example #5
{
"root": [
{
"@a": "one"
},
{
"@b": "two"
},
{
"@c": "three"
}
]
}
"`nExample #1"
[xml]'<root><node1>test</node1><node1>test2</node1><node1b>test3</node1b><node1c><node2>test4</node2><node2 id="attrtest">test5</node2></node1c></root>' | Convert-XmlToHash | ConvertTo-Json -Depth 100
"`nExample #2"
[xml]'<root><node1>hello</node1></root>' | Convert-XmlToHash | ConvertTo-Json -Depth 100
"`nExample #3"
[xml]'<root><node1 /></root>' | Convert-XmlToHash | ConvertTo-Json -Depth 100
"`nExample #4"
[xml]'<root />' | Convert-XmlToHash | ConvertTo-Json -Depth 100
"`nExample #5"
[xml]'<root a="one" b="two" c="three" />' | Convert-XmlToHash | ConvertTo-Json -Depth 100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment