Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

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

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...