需要使用Xpath替换XML文件中的属性值

时间:2012-12-31 09:52:46

标签: xml powershell xpath replace web-config

以下是源/目标XML(Web.Config)文件的内容,其中我必须替换属性的值。这需要为几个配置文件完成,因此需要您的帮助才能使用PowerShell完成此操作。我确实尝试使用代码来替换stackOverFlow中可用的字符串,但是dint使它成为..

<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->

<configuration>
<connectionStrings>

<add name="PrcEntities"
   providerName="System.Data.SqlClient"
   connectionString="Server=DDD05DB01,63518;Database=BBBDB001;Trusted_Connection=true;multipleactiveresultsets=true;Pooling=false"/>

<add name="CoreItemContext"
 providerName="System.Data.SqlClient"
 connectionString="Server=DDD15DB03,63520;Database=BBBDB002;Trusted_Connection=true;multipleactiveresultsets=true;Pooling=true"/>

</connectionStrings>
..

..

....

</configuration>

这是我的Powershell代码,用于从上面的XML文件

中查询名为“ConnectionString”的属性
$Path = "C:\Ps\Web.config" 
$con="connectionString"   
[xml]$Types = Get-Content $Path 
Select-Xml -Xml $Types -XPath "//add" | Select-Object -ExpandProperty Node|Select-Object name,$con | Format-List 

这将导致:

名称:PrcEntities connectionString:Server = DDD05DB01,63518; Database = BBBDB001; Trusted_Connection = true; multipleactiveresultsets = TRUE;池=假

name:CoreItemContext connectionString:Server = DDD15DB03,63520; Database = BBBDB002; Trusted_Connection = true; multipleactiveresultsets = TRUE;池=真

现在,我想用以下详细信息替换属性“ connectionString ”的值: Server = DBD05DB01,63518; Database = DDBDB001; Trusted_Connection = true; multipleactiveresultsets = true;两个地方的Pooling = false(PrcEntities&amp; CoreItemContext)

此更改应保存到同一源文件中。请帮我这个!!

1 个答案:

答案 0 :(得分:5)

$path = "D:\Web.Config"
[xml]$xml = Get-Content $path 

$xml.configuration.connectionStrings.add | Foreach-Object {
    $_.connectionString = 'Server=DBD05DB01,63518;Database=DDBDB001;Trusted_Connection=true;multipleactiveresultsets=true;Pooling=false'
}

$xml.Save($path)