4

我正在使用 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>

是否有一种方法可以在多行属性中保留换行符并在文件保存后保持缩进?

4

1 回答 1

4

设置格式需要使用 XmlWriterSettings 和 XmlWriter 类。前者设置了缩进、换行等格式。后者用于编写文档。两者都在 System.Xml 命名空间中可用。它们很容易在 Powershell 中使用。像这样,

  # Valid XML for example's sake
  [xml]$doc = @'
  <root>
  <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>
  </maintenance>
  </root>
  '@
  # Let's add Bob's machine. Create an element and add attributes
  $node = $doc.CreateElement("add")
  $node.SetAttribute("name", "Bobs Machine")
  $node.SetAttribute("address", "yy.yy.yyy.yy")
  $doc.root.maintenance.allowedIPAddresses.AppendChild($node)

  # Set up formatting
  $xwSettings = new-object System.Xml.XmlWriterSettings
  $xwSettings.indent = $true
  $xwSettings.NewLineOnAttributes = $true

  # Create an XmlWriter and save the modified XML document
  $xmlWriter = [Xml.XmlWriter]::Create("c:\temp\newlines.xml", $xwSettings)
  $doc.Save($xmlWriter)

输出(尽管标记删除了缩进):

  <?xml version="1.0" encoding="utf-8"?>
  <root>
    <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" />
      <add
      name="Bobs Machine"
      address="yy.yy.yyy.yy" />
    </allowedIPAddresses>
    </maintenance>
  </root>
于 2013-07-31T10:54:26.983 回答