How can I Force or Specify Encoding type using Xml.Save?

powershell, xml

Solution

This appears to take care of it. There could certainly be more elegant ways...

$xml = New-Object -TypeName XML
$xml.Load($file)
$xml.configuration.config.option = $newValue

$utf8WithoutBom = New-Object System.Text.UTF8Encoding($false)
$sw = New-Object System.IO.StreamWriter($file, $false, $utf8WithoutBom)

$xml.Save( $sw )
$sw.Close()

Details collected from here, here and here.

Problem

I have an XML configuration file I am modifying with PowerShell, and when I save the file using Xml.Save it changes the encoding type. When I open the ORIGINAL file I am trying to edit in Notepad++ the encoding type is listed as "UTF-8 without BOM". When I open the file in Notepad++ AFTER editing using Xml.Save the encoding type is listed simply as "UTF-8". This causes the program using this file to error out saying it can't parse to config properties. If I open the EDITED file in Notepad++, change the encoding type to "UTF-8 without BOM", and save the file. The program will then run without error. How can I force and or specify the `Xml.Save` to use the "UTF-8 without BOM" encoding type when saving the file? I have tried different ways of casting and saving file, but `Xml.Save` seems to default to the "UTF-8" enconding type. ``` $xml = New-Object -TypeName XML $xml.Load($file) $xml.configuration.config.option = $newValue $xml.Save($file) ```

Original source

Related problems