Skip to content

Instantly share code, notes, and snippets.

@jfromaniello
Created April 20, 2012 19:04
Show Gist options
  • Save jfromaniello/2431090 to your computer and use it in GitHub Desktop.
Save jfromaniello/2431090 to your computer and use it in GitHub Desktop.
##Usage
$a = Convert-JsonToXml "{foo: 1, bar: 2}"
write-host $a.root.foo
write-host $a.root.bar
###
###################### JSON PARSING
Add-Type -Assembly System.ServiceModel.Web,System.Runtime.Serialization
$utf8 = [System.Text.Encoding]::UTF8
function Write-Stream {
PARAM(
[Parameter(Position=0)]$stream,
[Parameter(ValueFromPipeline=$true)]$string
)
PROCESS {
$bytes = $utf8.GetBytes($string)
$stream.Write( $bytes, 0, $bytes.Length )
}
}
function Convert-JsonToXml {
PARAM([Parameter(ValueFromPipeline=$true)][string[]]$json)
BEGIN {
$mStream = New-Object System.IO.MemoryStream
}
PROCESS {
$json | Write-Stream -Stream $mStream
}
END {
$mStream.Position = 0
try
{
$jsonReader = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonReader($mStream,[System.Xml.XmlDictionaryReaderQuotas]::Max)
$xml = New-Object Xml.XmlDocument
$xml.Load($jsonReader)
$xml
}
finally
{
$jsonReader.Close()
$mStream.Dispose()
}
}
}
###################### END OF PARSING
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment