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

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

概述好的,所以这是我的web.config文件的片段: <?xml version="1.0" encoding="utf-8"?><configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"><location path="." inheritInChildApplications="false"><con 好的,所以这是我的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)
总结

以上是内存溢出为你收集整理的.在Powershell脚本中选择单个节点,使用xPath无法从web.config文件中提取值全部内容,希望文章能够帮你解决.在Powershell脚本中选择单个节点,使用xPath无法从web.config文件中提取值所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1107977.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-29
下一篇 2022-05-29

发表评论

登录后才能评论

评论列表(0条)

保存