简体   繁体   中英

Wrapping specific XML nodes in tags using XSLT

I am trying to transform a dataset using XSLT. Only one section should get additional tags.

<formData>
    <baseFields>
        <elementA>TEST</elementA>
        <elementB>TEST2</elementB>
    </baseFields>
    <dataFields>
        <groupA>
            <elementA>TEST</elementA>
            <elementB>TEST2</elementB>
        </groupA>
        <groupB>
            <elementA>TEST</elementA>
            <elementB>TEST2</elementB>
        </groupB>
    </dataFields>
</formData>

into

<formData>
    <elementA>TEST</elementA>
    <elementB>TEST2</elementB>
    <groupA>
        <elementA><asCurrent>TEST</asCurrent></elementA>
        <elementB><asCurrent>TEST2</asCurrent></elementB>
    </groupA>
    <groupB>
        <elementA><asCurrent>TEST</asCurrent></elementA>
        <elementB><asCurrent>TEST2</asCurrent></elementB>
    </groupB>
</formData>

The baseFields group and the dataFields group should be removed and nodes or text elements within the dataFields section should be wrapped in asCurrent tags.

Any help will be appreciated!

Update: Based on the help from Dan Field I was able to process this using the following XSLT.

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

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

    <xsl:template match="baseFields">
        <xsl:apply-templates />
    </xsl:template>

    <xsl:template match="dataFields">
        <xsl:apply-templates />
    </xsl:template>

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

    <xsl:template match="dataFields//text()">
            <asCurrent><xsl:copy><xsl:apply-templates select="text()"/></xsl:copy></asCurrent>
    </xsl:template>
</xsl:transform>

One approach is a simple identity transform with templates to match the tags you want to discard that just apply the next template:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml" encoding="UTF-8" indent="yes" />

     <xsl:strip-space elements="*"/>
    <xsl:template match="baseFields">
        <xsl:apply-templates />
    </xsl:template>

    <xsl:template match="dataFields">
        <xsl:apply-templates />
    </xsl:template>

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

XSLTransform

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