Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

powershell

xml

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)
like image 409
Jim P. Avatar asked May 15 '15 18:05

Jim P.


1 Answers

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.

like image 136
mcating Avatar answered Nov 03 '22 00:11

mcating