3

我正在尝试使用 Powershell 向 web.configsectionGroup中的元素添加一个元素configuration/configSections

我目前有

$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方法出现异常:

“指定的节点不能作为该节点的有效子节点插入,因为指定的节点类型错误。”

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

我尝试过的其他东西是

$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>元素吗?

4

1 回答 1

8

这应该这样做:

$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)
于 2013-06-17T08:17:21.750 回答