如何在 config install xdt transform 中指定节点的插入位置

How to specify insert location for node within config install xdt transform

我有一个正在尝试创建的 nuget 包,但似乎无法弄清楚如何使这最后一部分正常工作。我正在使用 config.install.xdt transforms 以将配置元素添加到客户端配置文件。

我只是在客户端配置文件中添加一个新的 <section> 节点,如下所示:

<?xml version="1.0" ?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
    <configSections xdt:Transform="InsertIfMissing">
        <section xdt:Transform="InsertIfMissing" xdt:Locator="Match(name)"
                 name="myPackageName" 
                 type="MyPackage.Config.MySection, MyPackage" />
    </configSections>
</configuration>

问题是 <configSections> 必须是客户端 app.config 中根 <configuration> 元素的第一个 child。如果客户端应用程序中不存在 <configSections>,则上述转换仅将 <configSections> 作为最后一个 child 添加到 <configuration>.

有什么方法可以强制将 <configSections> 作为 <configuration> 中的第一个 child 插入?

编辑 1

我想补充一些关于我尝试过的内容以及结果的详细信息...

我进行的第一个转换是 <configSections xdt:Transform="InsertIfMissing">。即使这是我的 config.install.xdt 文件中的第一个 child,它也会在安装时被放置在客户端配置文件的末尾。

我尝试了 InsertBefore 和 InsertAfter 变换的几种变体。不幸的是,我不能只使用,例如,<configSections xdt:Transform="InsertBefore(/configuration/appSettings)",因为 appSettings 元素可能并不总是存在于客户端配置文件中,也可能不是第一个 child 节点。

我认为这必须有一些功能,因为当将像 Entity Framework 这样的 nuget 包安装到一个配置文件还没有 <configSections> 节点的项目中时,<configSections> 节点作为第一个 child 添加到 <configuration> 根目录中,安装了 Entity Framework.

编辑 2

经过几个小时的搜索和用头撞墙,通过 Leo 的回答,我发现了另一个 Whosebug post,问题大致相同。我将我的问题标记为重复。这里是 link.

How to specify insert location for node within config install xdt transform

当您通过默认将nuget安装到项目时,<configSections>应该是客户端app.config中根元素的第一个子元素。

如您所知并在 documentation 中指定:

If this element is in a configuration file, it must be the first child element of the element

您可以在此处指定 app.config 中的配置部分,因此,它必须位于配置元素的开头。

因此默认情况下 <configSections> 应该是客户端 app.config 中根元素的第一个子元素,即使客户端应用程序中不存在 <configSections>

作为测试,我创建了一个带有 content 文件夹的简单测试 nuget 包,其中包括 App.config.transformWeb.config.transform。将您的代码复制到 .transform:

的内容中
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <configSections xdt:Transform="InsertIfMissing">
    <section xdt:Transform="InsertIfMissing" xdt:Locator="Match(name)"
             name="myPackageName"
             type="MyPackage.Config.MySection, MyPackage" />
  </configSections>
</configuration>

然后将这个 nuget 包安装到测试项目中:

除了,你可以在使用转换InsertBefore时尝试使用通配符*而不是appSettings,比如:

<configSections xdt:Transform="InsertBefore(/configuration/*[1])" />

希望这对您有所帮助。