我有以下 xml
<system.net>
<defaultProxy useDefaultCredentials="true" />
</system.net>
并且想使用 Powershell 将上面的“defaultProxy”节点替换为下面的节点
<system.net>
<defaultProxy>
<proxy usesystemdefault="True" proxyaddress="http://xxxxx" bypassonlocal="True" />
<bypasslist>
<add address="yyyyyy" />
</bypasslist>
</defaultProxy>
</system.net>
我见过类似的帖子,但没有看到嵌套节点。我就是无法理解它
这有点乏味,但你可以像这样构建一个新的
<defaultProxy />
替换:
# parse xml document
$configurationDoc = [xml]@'
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.net>
<defaultProxy useDefaultCredentials="true" />
</system.net>
</configuration>
'@
# create new <defaultProxy /> element
$newDefaultProxy = $configurationDoc.CreateElement('defaultProxy')
# create new <proxy /> element, add to previous element
$newProxy = $configurationDoc.CreateElement('proxy')
$newProxy.SetAttribute('usesystemdefault', $true)
$newProxy.SetAttribute('proxyaddress', "http://xxxxx")
$newProxy.SetAttribute('bypassonlocal', $True)
$newDefaultProxy.AppendChild($newProxy) |Out-Null
# create new <bypasslist /> element with child node, add to previous element
$newBPL = $configurationDoc.CreateElement('bypasslist')
$addresses = @('address_goes_here')
foreach($address in $addresses) {
$newAdd = $configurationDoc.CreateElement('add')
$newAdd.SetAttribute('address', $address)
$newBPL.AppendChild($newAdd) |Out-Null
}
$newDefaultProxy.AppendChild($newBPL) |Out-Null
# replace existing defaultProxy element, or append if not found
$existingDefaultProxy = $configurationDoc.SelectSingleNode('//defaultProxy')
if ($null -ne $existingDefaultProxy) {
$configurationDoc.ReplaceChild($newDefaultProxy, $existingDefaultProxy) |Out-Null
}
else {
$configurationDoc.AppendChild($newDefaultProxy) |Out-Null
}
保存文档:
$configurationDoc.Save($(Convert-Path path\to\export.xml))