我想读入一个XML文件并修改一个元素,然后将其保存回该文件。在保留格式的同时保持匹配的行终止符(CRLF vs LF)的最好方法是什么?
下面是我所拥有的,但它不能做到这一点:
$xml = [xml]([System.IO.File]::ReadAllText($fileName))
$xml.PreserveWhitespace = $true
# Change some element
$xml.Save($fileName)
问题是在我混合了LF和CRLF之后,额外的新行(也就是xml中的空行)被删除了。
发布于 2018-01-07 01:46:10
如果您希望在调用XmlDocument上的Save方法后为文本节点更正转换为LF的CRLF,则可以使用XmlWriterSettings实例。使用与MilesDavies192s answer相同的XmlWriter,但也将编码更改为utf-8并保持缩进。
$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()
}
发布于 2016-01-13 22:53:01
如果使用XmlWriter保存,则默认选项是缩进两个空格,并将行尾替换为CR/LF。您可以在创建编写器之后配置这些选项,也可以使用根据需要配置的XmlSettings对象创建编写器。
$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)
发布于 2018-11-07 23:50:06
我没有看到行尾改变(\r\n),除了最后一个消失了。但是,编码通过物料清单从ASCII码转换为UTF8。
$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
https://stackoverflow.com/questions/8160613
复制相似问题