Web.config partial search and replace

最后都变了- 提交于 2020-01-05 11:37:47

问题


I have App.config file in C# application. I want to partially replace all Keys matching ".UAT" with ".PROD" using xdt tranform.

<?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>

Here is the output I want

    <?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>

So far I've tried this using CustomTransform but it replaces only one element instead of all element. How can i get this to replace all elements

    <?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:


I found the answer here where I had to replace the Apply method with this method that iterates over all attributes

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);
            }
        }
    }
}


来源:https://stackoverflow.com/questions/31224858/web-config-partial-search-and-replace

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!