Web.config部分搜索和替换

时间:2015-07-04 20:26:09

标签: xdt-transform

我在C#应用程序中有App.config文件。 我想使用xdt tranform部分替换匹配“.UAT”与“.PROD”的所有键。

<?xml version="1.0"?>    
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">

<appSettings>
    <add key="MyParam1.UAT" value="param1"/>
    <add key="MyParam2.UAT" value="param2"/>
    <add key="MyParam2.UAT" value="param3"/>
  </appSettings>
</configuration>

这是我想要的输出

    <?xml version="1.0"?>    
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
        <appSettings>
            <add key="MyParam1.PROD" value="param1"/>
            <add key="MyParam2.PROD" value="param2"/>
            <add key="MyParam2.PROD" value="param3"/>
          </appSettings>
        </configuration>

到目前为止,我已经尝试使用CustomTransform,但它只替换了一个元素而不是所有元素。我怎样才能更换所有元素

    <?xml version="1.0"?>    
<!-- For more information on using web.config transformation visit http://go.microsoft.com/fwlink/?LinkId=125889 -->    
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">

<appSettings>
    <add xdt:Locator="Condition(contains(@key, '.UAT'))" xdt:Transform="AttributeRegexReplace(Attribute='key', Pattern='.UAT',Replacement='.PROD')" />
  </appSettings>
</configuration>

1 个答案:

答案 0 :(得分:0)

我找到了answer here,我必须用这种迭代所有属性的方法替换Apply方法

protected override void Apply()
{
    foreach (XmlNode target in this.TargetNodes)
    {
        foreach (XmlAttribute att in target.Attributes)
        {
            if (string.Compare(att.Name, this.AttributeName, StringComparison.InvariantCultureIgnoreCase) == 0)
            { // get current value, perform the Regex 
                att.Value = Regex.Replace(att.Value, this.Pattern, this.Replacement);
            }
        }
    }
}
相关问题