好的,所以这是我的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查看了示例,我似乎无法弄明白.不太确定我做错了什么.
谢谢,
麦克风
解决方法
您的XML文件具有命名空间:
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
所以你需要SelectSingleNode
的命名空间管理器(参见“备注”部分):
XPath expressions can include namespaces. Namespace resolution is supported using the XmlNamespaceManager. If the XPath expression includes a prefix,the prefix and namespace URI pair must be added to the XmlNamespaceManager.
像这样的东西应该工作:
$ns = New-Object System.Xml.XmlNamespaceManager($WebConfigXml.NaMetable) $ns.AddNamespace("ns",$WebConfigXml.DocumentElement.NamespaceURI) $node = $WebConfigXml.SelectSingleNode("//ns:add[@key='SiteDomain']",$ns)