I have been using this function to dump XML to the console for review as I work on code to do some extensive XML manipulation, and for the most part it works as expected.
function Write-PxXmlToConsole {
param (
[Xml.XmlNode]$Xml
)
if ($Xml -is [Xml.XmlDocument]) {
$xmlDocument = $Xml
} else {
$xmlDocument = [Xml.XmlDocument]::new()
$newElement = $xmlDocument.ImportNode($Xml, $True)
[Void]$xmlDocument.AppendChild($newElement)
}
$stringWriter = [System.IO.StringWriter]::new()
$xmlWriter = [System.Xml.XmlTextWriter]::new($stringWriter)
$xmlWriter.Formatting = "indented"
$xmlDocument.WriteTo($xmlWriter)
$xmlWriter.Flush()
$stringWriter.Flush()
Write-Host $stringWriter.ToString()
Write-Host
}
However, it seems that somewhere in the [System.IO.StringWriter]
variables are getting expanded. Because when my XML looks like this
$xml = [Xml]@"
<Pattern>$key.Value</Pattern>
"@
Write-PxXmlToConsole $xml
I get <Pattern>Autodesk Revit 2019.Value</Pattern>
as output because somewhere in this session the variable $key
got populated. And if I start a new session I will get <Pattern>.Value</Pattern>
. A bit of a pain, and I can't seem to find anything here that suggests a setting that would suppress this behavior.
Variables are getting expanded during creation of [Xml]
with double quotes:
$xml = [Xml]@"
<Pattern>$key.Value</Pattern>
"@
Write-Host $xml.Pattern
Write-PxXmlToConsole $xml
.Value
<Pattern>.Value</Pattern>
The output is different when single quotes are used:
$xml = [Xml]@'
<Pattern>$key.Value</Pattern>
'@
Write-Host $xml.Pattern
Write-PxXmlToConsole $xml
$key.Value
<Pattern>$key.Value</Pattern>