简体   繁体   中英

Transform xml based on child element using xslt

My xml contains two cases

Case 1:

<section>
            <title>Order Sections</title>
            <para>This function describes. </para>
</section>

Case 2:

<section>
            Band mode is Order
            <p outputclass="termtesttext">In this case a fixed order bandwidth.</p>
        </section>

I want the output to be:

Case 1:

<division>
                <title>Order Sections</title>
                <para>This function describes. </para>
    </division>

Case 2:

<division>
            <title>Band mode is Order</title>
            <para>In this case a fixed order bandwidth.</para>
        </division>

I have used identity transform in the beginning to copy everything.

Would this work for you:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

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

<xsl:template match="section">
    <division>
        <xsl:apply-templates select="node()"/>
    </division>
</xsl:template>

<xsl:template match="section/text()">
    <title>
        <xsl:value-of select="normalize-space(.)"/>
    </title>
</xsl:template>

<xsl:template match="section/p">
    <para>
       <xsl:apply-templates/>
    </para>
</xsl:template>

</xsl:stylesheet>

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