简体   繁体   中英

XSLT apply template on every text node

I have a complex transformation from one xml format to another and need to trim all the possible leading and tailing whitespaces on every text element after the transformation.

XML input is something like:

<Records>
  <Record>
    <FirstName>FIRST</FirstName>
    <MiddleName>MID</MiddleName>
    <LastName>LAST</LastName>
    <VehType>PCAR</VehType>
    <VehType2>VN</VehType2>
    <VehMake>CHEV</VehMake>
    <VehModel>AST</VehModel>
    <VehColor>DBL</VehColor>
    <VehVIN>1234123</VehVIN>
  </Record>
</Records>

And stylesheet example is:

<xsl:template match="Record">
    <MyRecord>
        <NameRecord>
            <FirstName>
                <xsl:value-of select="FirstName" />
            </FirstName>
            <MiddleName>
                <xsl:value-of select="MiddleName" />
            </MiddleName>
            <LastName>
                <xsl:value-of select="LastName" />
            </LastName>
        </NameRecord>
        <VehicleRecord>
            <VehicleType>
                <xsl:value-of select="VehType" />
            </VehicleType>
            <MakeOfCar>
                <xsl:value-of select="VehMake" />
            </MakeOfCar>
            <ModelOfCar>
                <xsl:value-of select="VehModel" />
            </ModelOfCar>
            <ColorPrimary>
                <xsl:value-of select="VehColor" />
            </ColorPrimary>
            <VehicleIDNumber>
                <xsl:value-of select="VehVIN" />
            </VehicleIDNumber>
            <YearOfCar>
                <xsl:value-of select="VehYear" />
            </YearOfCar>
        </VehicleRecord>
    </MyRecord>
</xsl:template>

But more complex with a lot of levels and inclusions. Problem is, any incoming xml element may contain data like <VehVIN> 1234123 </VehVIN> and I need to trim leading and tailing whitespaces. Found this beautiful solution and tried to integrate it in to my stylesheet, but no luck.

<xsl:template match="text()">
    <xsl:call-template name="string-trim">
        <xsl:with-param name="string" select="." />
    </xsl:call-template>
</xsl:template>

Instead of doing this...

<xsl:value-of select="FirstName" />

Do this, as this will then allow your text() template to match

<xsl:apply-templates select="FirstName/text()" />

And similarly for the other elements.

Infact, you can just to <xsl:apply-templates select="FirstName" /> as XSLT's built-in template will match FirstName which will then skip over the node and select its child nodes.

You can use the following template:

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

It removes all leading and trailing spaces on every text element.

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