。在Powershell脚本中选择单个节点,使用xPath无法从web.config文件中提取值

时间:2013-09-18 19:34:39

标签: powershell xpath web-config selectsinglenode

好的,所以这是我的web.config文件的片段:

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<location path="." inheritInChildApplications="false">
<connectionStrings>
...
</connectionStrings>
</location>
<location path="." inheritInChildApplications="false">
<appSettings>
<!--IT Ops-->
<add key="SomeOtherKey" value="SomeOtherValue" />
<add key="SiteDomain" value="somedomain.com" />
<add key="SomeOtherKey" value="SomeOtherValue" />
....
</appSettings>
</location>
</configuration>

我要做的是通过Powershell使用xPath找到节点。有关此XML文件的几点注意事项:

有多个:

<location path="." inheritInChildApplications="false"> 

xml文件中的值。它们包围着其他节点......等等。

我可以使用此脚本

成功找到并替换连接字符串值
$WebConfigFile = Join-Path $destination Web.config
[xml]$WebConfigXml = Get-Content ($WebConfigFile)
$WebConfigXml.configuration.location[2].connectionStrings.add | % { $_.connectionString = $_.connectionString -replace "some value", $sqlServerName }

但是当我使用这个脚本替换add key =“SiteDomain”值时:

$node = $WebConfigXml.configuration.location[3].appSettings.SelectSingleNode("add[@key = 'SiteDomain']")
$node.value = "someValue"
$WebConfigXml.Save($WebConfigFile)

它不起作用。在这种情况下,$ node值包含一个空字符串。

我也试图像这样阅读节点:

$appSettingsSection = $WebConfigXml.configuration.location[3].appSettings;
$existingSiteDomain = $appSettingsSection.SelectSingleNode("add[@key='SiteDomain']")

我仍然为$ existingSiteDomain值获取一个空字符串。

我使用SelectSingleNode查看了示例,我似乎无法弄明白。不太确定我做错了什么。

谢谢, 麦克

2 个答案:

答案 0 :(得分:20)

您的XML文件有一个命名空间:

<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">

因此您需要SelectSingleNode的命名空间管理器(请参阅“备注”部分):

  

XPath表达式可以包含名称空间。使用 XmlNamespaceManager 支持命名空间解析。如果XPath表达式包含前缀,则必须将前缀和名称空间URI对添加到 XmlNamespaceManager

这样的事情应该有效:

$ns = New-Object System.Xml.XmlNamespaceManager($WebConfigXml.NameTable)
$ns.AddNamespace("ns", $WebConfigXml.DocumentElement.NamespaceURI)
$node = $WebConfigXml.SelectSingleNode("//ns:add[@key='SiteDomain']", $ns)

答案 1 :(得分:0)

其他替代方法是使用 Select-Xml cmdlet:

$nameSpace = @{ x=$WebConfigXml.DocumentElement.NamespaceURI }    
$result = Select-Xml -Xml $WebConfigXml -XPath "//ns:add[@key='SiteDomain']" -Namespace $nameSpace