【问题标题】:How to insert <configSections> as first child in app.config如何在 app.config 中插入 <configSections> 作为第一个子项
【发布时间】:2019-01-16 14:01:43
【问题描述】:

我目前正在创作一个新的 NuGet 包,但我无法正确获取 app.config.install.xdt 文件(这是转换 app.config 以适应已安装的包)。

问题是在 app.config 中插入一个 部分作为第一个子项 - 但仅限于它丢失的情况!

它必须是第一个孩子,否则应用程序将失败并出现异常(Microsoft 强制执行)。

如果我只使用常规的 “InsertIfMissing” 转换,插入发生在 任何现有的子级之后,所以这似乎是不行的。

我可以做些什么来解决我的问题?

【问题讨论】:

    标签: visual-studio-2017 nuget app-config xdt-transform xdt


    【解决方案1】:

    我遇到了完全相同的问题并以这种方式解决了它:

    <configSections xdt:Transform="InsertBefore(/configuration/*[1])" />
    <configSections xdt:Locator="XPath(/configuration/configSections[last()])">
         do_your_stuff_with_sections_here...
    </configSections>
    <configSections xdt:Transform="RemoveAll" xdt:Locator="Condition(count(*)=0)" />
    

    第一行无条件地将节点创建为第一个子节点:

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

    第二行确保您对最后一个 configSections 节点进行了所有编辑,如果它已经存在,则该节点是正确的节点……

    <configSections xdt:Locator="XPath(/configuration/configSections[last()])">
    

    在 de configSections 块中执行转换后,输入一个删除所有空 configSections 节点的命令...(最后一行)

    <configSections xdt:Transform="RemoveAll" xdt:Locator="Condition(count(*)=0)" />
    

    【讨论】:

    • 很好的解决方案。不知道为什么这没有被标记为答案。
    【解决方案2】:

    我也在寻找解决方案...

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

    【讨论】:

    • 如果不确定节点是否为空,请注意删除节点
    【解决方案3】:

    如何在 app.config 中作为第一个子项插入

    您可以利用属性xdt:Transform="InsertBefore" 在该部分中插入一个新元素,但在任何其他元素之前,例如:

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

    证书:XDT Transform: InsertBefore - Locator Condition is ignored

    有关更多详细信息,请参阅How to use XDT in NuGet - Examples and Facts

    希望这会有所帮助。

    【讨论】:

    • 并非如此。问题是该部分是无条件插入的。这意味着,如果我删除 nuget 包并重新安装它,我会留下 两个 -children 而不仅仅是一个。必须只有一个,并且必须始终是第一个孩子。
    猜你喜欢
    • 2011-05-30
    • 2012-11-24
    • 1970-01-01
    • 2014-12-17
    • 2011-03-03
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    相关资源
    最近更新 更多