Web 配置转换:如果不存在则插入

问题描述 投票:0回答:4

当且仅当目标中不存在匹配元素时,我想应用转换。使用 http://webconfigtransformationtester.apphb.com/ 尝试各种 xpath 表达式,但到目前为止还没有运气。

例如如果目标 web.config 看起来像这样:

<configuration> <system.web> <compilation debug="true" /> </system.web> </configuration>

那么输出应该如下所示:

<configuration> <connectionStrings> <add name="MyCs" provider="System.Data.SqlClient" connectionString="" /> <add name="SomeOtherCs" provider="System.Data.SqlClient" connectionString="" /> </connectionStrings> <system.web> <compilation debug="true" /> </system.web> </configuration>

但是如果目标看起来像这样:

<configuration> <connectionStrings> <add name="MyCs" provider="System.Data.IChangedIt" connectionString="my connection string here" /> </connectionStrings> <system.web> <compilation debug="true" /> </system.web> </configuration>

那么转换的结果应该是这样的:

<configuration> <connectionStrings> <add name="MyCs" provider="System.Data.IChangedIt" connectionString="my connection string here" /> <add name="SomeOtherCs" provider="System.Data.SqlClient" connectionString="" /> </connectionStrings> <system.web> <compilation debug="true" /> </system.web> </configuration>

换句话说,我只想将命名连接字符串添加到配置中,但让管理员用自己的值填充它。我认为它会像

xdt:Transform="Insert" xdt:Locator="XPath(count(/configuration/connectionStrings)=0)"

 一样简单(如果不存在,则添加 cs 配置部分),但显然不是。

xpath web-config web-config-transform
4个回答
69
投票

xdt:Transform="InsertIfMissing"

 与 VS2012 中的 
XmlTransform
 任务一起使用。微软似乎还没有更新他们的文档来反映这一点。


48
投票
就我而言,如果没有

xdt:Transform="InsertIfMissing"

xdt:Locator="Match(name)"
就无法工作


12
投票
尝试使用

xdt:Transform="InsertIfMissing" : 的替代转换

<?xml version="1.0"?> <configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> <nodeToInsertIfMissing xdt:Transform="Insert" /> <nodeToInsertIfMissing xdt:Transform="Remove" xdt:Locator="XPath(/configuration/nodeToInsertIfMissing[2])" /> </configuration>

它应该按照

MSDN 文档工作:

Insert - 将转换文件中定义的元素添加为所选元素的同级元素。新元素会添加到任何集合的末尾

因此,如果该节点已经存在,我们添加第二个节点,然后删除该节点(第二个)。否则,我们添加新的、唯一的节点,但删除操作将失败。

注意:它似乎不适用于 NuGet

*.(un)install.xdt 转换。 也插入IfMissing


5
投票
已确认在 VS2015 和包管理器控制台主机版本 3.4.4.1321 中工作(打开包管理器控制台时可以找到它)。

这将插入 if 'configuration

© www.soinside.com 2019 - 2024. All rights reserved.