gpt4 book ai didi

Powershell - 如何将 添加到 web.config

转载 作者:行者123 更新时间:2023-12-03 09:54:34 24 4
gpt4 key购买 nike

我正在尝试添加 sectionGroup configuration/configSections 的元素使用 Powershell 的 web.config 中的元素。

我现在有

$filePath = [path to my web.config file]

# load the XML from the web.config
$xml = New-Object XML
$xml = [xml](Get-Content $filePath)

# navigate to the <configSections> element
$xmlConfigSections = $xml.SelectSingleNode("//configuration/configSections")

# create the new <sectionGroup> element with a 'name' attribute
$sectionGroup = $xml.CreateElement("sectionGroup")
$xmlAttr = $xml.CreateAttribute("name")
$xmlAttr.Value = "myCustomSectionGroup"
$sectionGroup.Attributes.Append($xmlAttr)

# now add the new <sectionGroup> element to the <configSections> element
$xmlConfigSections.AppendChild($sectionGroup)

#save the web.config
$xml.Save($filePath)

但这会在 CreateElement 上引发异常方法:

"The specified node cannot be inserted as the valid child of this node, because the specified node is the wrong type."

我不明白为什么当我尝试创建元素时会抛出这样的异常(异常似乎与附加元素有关)。

我尝试过的其他方法是

$newConfig = [xml]@'<sectionGroup name="myCustomSectionGroup"></sectionGroup>'@

$filePath = [path to my web.config file]

# load the XML from the web.config
$xml = New-Object XML
$xml = [xml](Get-Content $filePath)

# navigate to the <configSections> element
$xmlConfigSections = $xml.SelectSingleNode("//configuration/configSections")

$xmlConfigSections.AppendChild($newConfig)

但这会引发与之前完全相同的异常。

<sectionGroup>绝对是 <configSections> 的有效子代.

理想情况下,我希望第二次尝试成功,因为这不需要我声明每个元素、每个属性、

谁能解释一下为什么 <configSections>节点不允许我的 <sectionGroup>元素?

最佳答案

应该这样做:

$filePath = [path to my web.config file]

# load the XML from the web.config
$xml = New-Object XML
$xml = [xml](Get-Content $filePath)

$sectionGroup = $xml.CreateElement('sectionGroup')
$sectionGroup.SetAttribute('name','myCustomSectionGroup')
$sectionGroupChild = $xml.CreateElement('sectionGroupChild')
$sectionGroupChild.SetAttribute('name','myCustomSectionGroup')

$newNode = $xml.configuration.configSections.AppendChild($sectionGroup)
$newNode.AppendChild($sectionGroupChild)

$xml.Save($filePath)

关于Powershell - 如何将 <sectionGroup> 添加到 web.config,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17135545/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com