首页 > 解决方案 > 避免使用powershell从xml文件中删除空行

问题描述

基本上问题是原始 xml 文件 ( $myFilePath) 在文件中有空行,但是在保存 xml 文件时,空行被删除。

保存时如何避免从文件中删除空行?

以下是我尝试过的 -

$myXmlDocument = [xml] (Get-Content -Path $myFilePath) # File ready style-1
$myXmlDocument = [xml]([System.IO.File]::ReadAllText($myFilePath)) # File ready style-2

$myXmlDocument.PreserveWhitespace = $true #additional setting to preserver the format

#performing some string match and update. without the update also having same issue of blank line removal while saving.

$WadiAPConfigXmlDocument.Save($myFilePath) # saving the file

标签: xmlpowershell

解决方案


您需要在加载文件之前PreserveWhitespace设置属性:

# Create XmlDocument object and configure PreserveWhitespace
$xmlDoc = [xml]::new()
$xmlDoc.PreserveWhitespace = $true

# Load the document
$xmlDoc.Load($myFilePath)
# or 
$xmlDoc.LoadXml($(Get-Content $myFilePath -Raw))

推荐阅读