【问题标题】:Need to replace value of an attribute in XML file using Xpath需要使用 Xpath 替换 XML 文件中属性的值
【发布时间】:2012-12-15 12:33:21
【问题描述】:

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

<?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 连接字符串:服务器=DDD05DB01,63518;数据库=BBBDB001;Trusted_Connection=true; multipleactiveresultsets=true;Pooling=false

名称:CoreItemContext 连接字符串:服务器=DDD15DB03,63520;数据库=BBBDB002;Trusted_Connection=true; multipleactiveresultsets=true;Pooling=true

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

此更改应保存到同一源文件。请帮我解决这个问题!

【问题讨论】:

    标签: xml powershell xpath replace web-config


    【解决方案1】:
    $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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-13
      • 1970-01-01
      • 1970-01-01
      • 2018-12-11
      • 2011-08-31
      • 2012-11-15
      • 2012-08-03
      • 2020-08-02
      相关资源
      最近更新 更多