我正在使用 Powershell 来读取和修改 web.config 文件,所有操作都成功执行,但是在保存文件时我失去了缩进和多行属性的新中断。这是 web.config 文件在编辑之前的样子:
<maintenance isSet="false" startDate="2012-03-07T00:00:00" endDate="2012-03-07T23:59:59">
<allowedIPAddresses>
<add name="Johns Machine" address = "xx.xx.xxx.xx" />
<add name="Marys Machine" address = "xx.xx.xxx.xx" />
</allowedIPAddresses>
这是编辑 xml 的 Powershell 代码:
$script:myXML = New-Object System.Xml.XmlDocument
$myXML.PreserveWhitespace = $true
$myXML.CreateXmlDeclaration("1.0","iso-8859-1",$null)
$myXML.Load("C:\dev\web.config")
$ipEntries = $myXML.SelectNodes("/maintenance/allowedIPAddresses")
foreach ($ipEntry in $ipEntries)
{
$ipEntry.RemoveAll()
}
$reader = new-object System.IO.StreamReader($ipTextFile)
$i = 0
while(($line = $reader.ReadLine()) -ne $null)
{
$i++
$node = $myXML.CreateElement("add")
$node.SetAttribute("name", "Machine " + ($i))
$node.SetAttribute("address", $line)
$myXML.SelectSingleNode("/configuration/maintenance/allowedIPAddresses").AppendChild($node)
}
$myXML.Save("C:\dev\web.config")
这是脚本运行后的文件
<maintenance isSet="false" startDate="2012-03-07T00:00:00" endDate="2012-03-07T23:59:59">
<allowedIPAddresses><add name="Johns Machine" address="xx.xx.xxx.xx" /><add name="Marys Machine" address="xx.xx.xxx.xx" /></allowedIPAddresses>
是否有一种方法可以在多行属性中保留换行符并在文件保存后保持缩进?