首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Powershell保存XML和保留格式

Powershell保存XML和保留格式
EN

Stack Overflow用户
提问于 2011-11-17 08:21:02
回答 3查看 25.8K关注 0票数 31

我想读入一个XML文件并修改一个元素,然后将其保存回该文件。在保留格式的同时保持匹配的行终止符(CRLF vs LF)的最好方法是什么?

下面是我所拥有的,但它不能做到这一点:

代码语言:javascript
复制
$xml = [xml]([System.IO.File]::ReadAllText($fileName))
$xml.PreserveWhitespace = $true
# Change some element
$xml.Save($fileName)

问题是在我混合了LF和CRLF之后,额外的新行(也就是xml中的空行)被删除了。

EN

回答 3

Stack Overflow用户

发布于 2018-01-07 01:46:10

如果您希望在调用XmlDocument上的Save方法后为文本节点更正转换为LF的CRLF,则可以使用XmlWriterSettings实例。使用与MilesDavies192s answer相同的XmlWriter,但也将编码更改为utf-8并保持缩进。

代码语言:javascript
复制
$xml = [xml]([System.IO.File]::ReadAllText($fileName))
$xml.PreserveWhitespace = $true

# Change some element

#Settings object will instruct how the xml elements are written to the file
$settings = New-Object System.Xml.XmlWriterSettings
$settings.Indent = $true
#NewLineChars will affect all newlines
$settings.NewLineChars ="`r`n"
#Set an optional encoding, UTF-8 is the most used (without BOM)
$settings.Encoding = New-Object System.Text.UTF8Encoding( $false )

$w = [System.Xml.XmlWriter]::Create($fileName, $settings)
try{
    $xml.Save( $w )
} finally{
    $w.Dispose()
}
票数 9
EN

Stack Overflow用户

发布于 2016-01-13 22:53:01

如果使用XmlWriter保存,则默认选项是缩进两个空格,并将行尾替换为CR/LF。您可以在创建编写器之后配置这些选项,也可以使用根据需要配置的XmlSettings对象创建编写器。

代码语言:javascript
复制
    $fileXML = New-Object System.Xml.XmlDocument

    # Try and read the file as XML. Let the errors go if it's not.
    [void]$fileXML.Load($file)

    $writerXML = [System.Xml.XmlWriter]::Create($file)
    $fileXML.Save($writerXML)
票数 2
EN

Stack Overflow用户

发布于 2018-11-07 23:50:06

我没有看到行尾改变(\r\n),除了最后一个消失了。但是,编码通过物料清单从ASCII码转换为UTF8。

代码语言:javascript
复制
$a = get-content -raw file.xml
$a -replace '\r','r' -replace '\n','n'

<?xml version="1.0" encoding="utf-8"?>rn<Configuration>rn  <ViewDefinitions />rn</Configuration>rn

[xml]$b = get-content file.xml
$b.save('file.xml')

$a = get-content -raw file.xml
$a -replace '\r','r' -replace '\n','n'

<?xml version="1.0" encoding="utf-8"?>rn<Configuration>rn  <ViewDefinitions />rn</Configuration>

# https://gist.github.com/jpoehls/2406504
get-fileencoding file.xml

UTF8
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8160613

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档