Sha*_*neC 4 .net xml powershell web-config
我正在使用 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>
Run Code Online (Sandbox Code Playgroud)
以下是编辑 xml 的 Powershell 代码:
<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>
Run Code Online (Sandbox Code Playgroud)
这是脚本运行后的文件
<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>
Run Code Online (Sandbox Code Playgroud)
是否有一种方法可以在多行属性中保留换行符并在保存文件后保持缩进?
设置格式需要使用 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)
Run Code Online (Sandbox Code Playgroud)
输出(不过,标记删除了缩进):
<?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>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3190 次 |
最近记录: |