简体   繁体   中英

Insert XML node at first position using XSL

The XSLT will currently insert the import if it doesn't exist

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    ...
    ...
    <Import Project="$(SolutionDir)BuildShared.targets" />
</Project>

I need it to insert it as the first node

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <Import Project="$(SolutionDir)BuildShared.targets" />
    ...
    ...
</Project>

template.xsl;

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ms="http://schemas.microsoft.com/developer/msbuild/2003">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

    <xsl:template match='@*|node()'>
        <xsl:copy>
            <xsl:apply-templates select='@*|node()'/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="/ms:Project[not(ms:Import[@Project='$(SolutionDir)BuildConfiguration.targets'])]">
        <xsl:copy>          
            <xsl:apply-templates select="node()|@*"/>
            <Import xmlns="http://schemas.microsoft.com/developer/msbuild/2003" Project="$(SolutionDir)BuildConfiguration.targets"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

Swapping the import and apply-templates lines gives;

runtime error: file template.xsl line 9 element copy

Attribute nodes must be added before any child nodes to an element.

Just do your xsl:apply-templates for node() and @* separately:

<xsl:template match="/ms:Project[not(ms:Import[@Project='$(SolutionDir)BuildConfiguration.targets'])]">
    <xsl:copy>          
        <xsl:apply-templates select="@*"/>
        <Import xmlns="http://schemas.microsoft.com/developer/msbuild/2003" Project="$(SolutionDir)BuildConfiguration.targets"/>
        <xsl:apply-templates select="node()"/>
    </xsl:copy>
</xsl:template>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM