XmlDocument.WriteContentTo(xmlwriter)没有写入我的流

时间:2016-06-30 19:06:55

标签: xml powershell xml-parsing xmlwriter

我写了一个小函数,它格式化XmlDocument的缩进并保留UTF-8编码。问题是我似乎无法WriteContentTo我的XmlWriter实例。我的实现错了吗?

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
} 

1 个答案:

答案 0 :(得分:2)

在将流转储到数组之前,需要刷新writer。

数据位于内部缓冲区中。这是为了在写入文件/套接字等时进行优化。编写更大的数据块然后一次只写入字节更有效。刷新(以及关闭)可确保将内部缓冲区中的数据写入实际目标。 (请注意,此处还有一个级别,因为您使用XmlWriter和MemoryStream并刷新写入器刷新流)