Search code examples
xmlpowershellxml-parsingxmlwriter

XmlDocument.WriteContentTo(xmlwriter) not writing to my stream


I wrote a small function that formats an XmlDocument's indentation and preserves UTF-8 encoding. Problem is that I can't seem to WriteContentTo my XmlWriter instance. Is my implementation wrong on this?

function Format-XML ([xml]$xml, $indentChars = "  ")
{
        $xmlSettings = New-Object System.Xml.XmlWriterSettings
        $xmlSettings.Indent = $True
        $xmlSettings.IndentChars = $indentChars
        $xmlSettings.Encoding = $global:Utf8NoBomEncoding
        $xmlSettings.NewLineChars = "\r\n"
        $xmlSettings.NewLineHandling = [System.Xml.NewLineHandling]::Replace

        $xmlMemoryStream =  New-Object System.IO.MemoryStream
        $xmlWriter = [System.Xml.XmlWriter]::Create($xmlMemoryStream, $xmlSettings)
        $xml.WriteContentTo($xmlWriter)
        $formatedAndEncodedXMLString = [System.Text.Encoding]::UTF8.GetString($xmlMemoryStream.ToArray())
        $XmlWriter.Flush()
        Write-Output $formatedAndEncodedXMLString
} 

Solution

  • You need to flush the writer before dumping the stream to the array.

    Data was sitting in internal buffers. This is to optimize when writing to files/sockets etc. It is more effective to write a bigger block of data then just on byte at a time. Flushing (as well as closing) makes sure that data from internal buffers are written to the actual target. (note that there is one more level here since you use XmlWriter and MemoryStream and flushing the writer flushes the stream)