编辑 XML 对象 - 连接字符串 [英] Editing an XML object - Connection Strings
问题描述
我将一个 XML 配置作为名为 $appConfig
的 xml 对象加载到我的脚本中.我正在尝试用我自己的字符串替换连接字符串值.这是我到目前为止找到目标字符串的内容:
I have an XML config loaded into my script as an xml object called $appConfig
. I am trying to replace the connection string value with a string of my own. This is what I have so far which finds the target string:
$appConfig.configuration.connectionStrings.add |
? {$_.name -eq $dbName} |
select connectionString
我本质上想要类似这样的东西:
I essentially want something akin to this:
$appConfig.configuration.connectionStrings.add |
? {$_.name -eq $dbName} |
select connectionString = $updatedConnectionString
我很确定我需要创建一个变量并用 $appConfig
填充它,但每次我尝试时我都会得到另一个 XML 对象,而不是编辑目标 $appConfig
对象.我将 $appConfig
写回其原始文件位置并完成编辑.我似乎在这里找不到正确的语法.
I'm pretty sure I need to make a variable and populate it with the $appConfig
but everytime I try I just end up with another XML object instead of editing the target $appConfig
object as intended. I write the $appConfig
back to its original file location and complete the edit. I just can't seem to get the right syntax here.
我与字符串相关的 XML 示例:
My XML example related to the strings:
<configuration>
<connectionStrings>
<add name="db" connectionString="Data Source=(local);Initial Catalog=MyDB;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="dbFiles" connectionString="Data Source=(local);Initial Catalog=MyDB;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="dbReporting" connectionString="Data Source=(local);Initial Catalog=MyDB;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="Logging" connectionString="Data Source=(local);Initial Catalog=MyDB;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
推荐答案
如果你想使用点符号,你可以这样做:
If you want to use dot-notation, you could do something like this:
$node = $appConfig.configuration.connectionStrings.add |
Where-Object {$_.name -eq $dbName}
$node.connectionString = $updatedConnectionString
$appConfig.Save()
或像这样(如果您不想在修改其属性之前将所选节点分配给变量):
or like this (if you don't want to assign the selected node to a variable before modifying its attribute):
($appConfig.configuration.connectionStrings.add | Where-Object {$_.name -eq $dbName}).connectionString = $updatedConnectionString
$appConfig.Save()
另一种方法是将 SelectSingleNode()
方法与 XPath 表达式一起使用,例如像这样:
Another way would be to use the SelectSingleNode()
method with an XPath expression, e.g. like this:
($appConfig.SelectSingleNode("//add[@name='$dbName']").connectionString = $updatedConnectionString
$appConfig.Save()
这篇关于编辑 XML 对象 - 连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!