如何使用 xslt 将 <configSections> 添加到 web.config

How can I add <configSections> to web.config using xslt

我需要使用 xslt 修改 web.config。我们无法直接访问实际的 web.config pre 或 post 转换。修改它的唯一机制是使用 xslt。

我写了一个 xslt 可以成功添加其他节点。如果它们存在,我可以添加子节点,或创建父节点,必要时添加子节点。

问题出在 <configSections> 它需要是 <configuration> 下的第一个节点,否则 IIS 会报错。如果保证存在,这将不是问题,但事实并非如此。无论我尝试了什么,我都无法强制结果可靠地将 <configSections> 节点作为第一个节点。

在我下面的示例中,如果 <configSections> 不存在,它会将新的 <configSections> 放在顶部,但如果它确实存在,它会将其添加到任意位置(在<configuration> 标签)。

我到处搜索,但找不到这个看似简单的问题的解决方案,所以我希望 XSLT 专家能告诉我它真的很简单。应该注意我在 xslt(!)

完全是个傻瓜

样本来源xml:

    <configuration>
       <appSettings>
       ...
       </appSettings>
       <otherStuff/>
    </configuration>

我的 Xslt:

<!-- Identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<!--If <configSections> exists, then add in my <section> node-->
<xsl:template match="configSections">
    <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <section name="mySectionHandler"/>
        <xsl:apply-templates select="node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="configuration">
    <xsl:copy>
        <xsl:apply-templates select="@*"/>      
        <xsl:if test="not(configSections)">
            <configSections>
                <section name="mySection"/>
           </configSections>
        </xsl:if>
        <xsl:if test="not(system.web)">
            <system.web>
                <httpRuntime executionTimeout="180" maxRequestLength="65536"/>
            </system.web>
        </xsl:if>
        <xsl:apply-templates select="node()"/>
    </xsl:copy>
</xsl:template>

我不确定您在任意位置添加 configSections(如果确实存在)是什么意思。您的 XSLT 会将它放在输出中的相同位置,但当 system.web 不存在时除外,因为您的 XSLT 然后会将 system.web 放在任何现有的 configSections[ 之前=16=]

无论如何,试试这个 XSLT。这应该 select 任何现有的 configSections 首先,如果它不存在则添加一个。然后在最后,它可以 select 所有其他元素。

<xsl:template match="configuration">
    <xsl:copy>
        <xsl:apply-templates select="@*"/>  
        <xsl:apply-templates select="configSections"/>
        <xsl:if test="not(configSections)">
            <configSections>
                <section name="mySection"/>
           </configSections>
        </xsl:if>
        <xsl:if test="not(system.web)">
            <system.web>
                <httpRuntime executionTimeout="180" maxRequestLength="65536"/>
            </system.web>
        </xsl:if>
        <xsl:apply-templates select="node()[not(self::configSections)]"/>
    </xsl:copy>
</xsl:template>