如何使用 Xml.Save 强制或指定编码类型? [英] How can I Force or Specify Encoding type using Xml.Save?

查看:41
本文介绍了如何使用 Xml.Save 强制或指定编码类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在使用 PowerShell 修改的 XML 配置文件,当我使用 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.

当我打开我试图在 Notepad++ 中编辑的原始文件时,编码类型被列为UTF-8 without BOM".当我在使用 Xml.Save 编辑后在 Notepad++ 中打开文件时,编码类型被简单地列为UTF-8".这会导致使用此文件的程序出错,说它无法解析为配置属性.

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.

如果我在 Notepad++ 中打开 EDITED 文件,将编码类型更改为UTF-8 without BOM",然后保存文件.然后程序将无误地运行.

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.

如何在保存文件时强制和/或指定 Xml.Save 使用UTF-8 without BOM"编码类型?

How can I force and or specify the Xml.Save to use the "UTF-8 without BOM" encoding type when saving the file?

我尝试了不同的转换和保存文件的方法,但 Xml.Save 似乎默认为UTF-8"编码类型.

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)

推荐答案

这似乎解决了它.当然可以有更优雅的方式......

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()

此处收集的详细信息这里这里.

这篇关于如何使用 Xml.Save 强制或指定编码类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆