问题
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