0

Hello I have a question related to transforming an input XML to an output XML using XSLT and removing the line breaks and indents just for some of the elements.

I would like to illustrate my question:

Input:

<LISTESTOF>
  <ICSGROUP>
    <ICSNUM>1</ICSNUM>
    <ICSDKNAME>A1</ICSDKNAME>
    <ICSUKNAME>B2</ICSUKNAME>
  </ICSGROUP>
  <ICSGROUP>
    <ICSNUM>2</ICSNUM>
    <ICSDKNAME>B1</ICSDKNAME>
    <ICSUKNAME>B2</ICSUKNAME>
  </ICSGROUP>
</LISTESTOF>

Output:

<LISTESTOF>
<ICSGROUP><ICSNUM>1</ICSNUM>
<ICSDKNAME>A1</ICSDKNAME>
<ICSUKNAME>B2</ICSUKNAME></ICSGROUP>
<ICSGROUP><ICSNUM>2</ICSNUM>
<ICSDKNAME>B1</ICSDKNAME>
<ICSUKNAME>B2</ICSUKNAME></ICSGROUP>
</LISTESTOF>

My XSLT file so far:

<?xml version="1.0" encoding="UTF-8"?>
<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="no"/>
    <xsl:strip-space elements="*"/>

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

    <xsl:template match="LISTESTOF">
             <xsl:value-of select="'&#xA;'" /><LISTESTOF><xsl:apply-templates select="ICSGROUP"/></LISTESTOF>
    </xsl:template>

    <xsl:template match="ICSGROUP">
              <xsl:value-of select="'&#xA;'" /><ICSGROUP><xsl:apply-templates select="ICSNUM"/><xsl:value-of select="'&#xA;'" /><xsl:apply-templates select="ICSDKNAME"/><xsl:value-of select="'&#xA;'" /><xsl:apply-templates select="ICSUKNAME"/></ICSGROUP>
    </xsl:template>

    <xsl:template match="ICSNUM">
        <ICSNUM><xsl:value-of select="."/></ICSNUM>
    </xsl:template>

    <xsl:template match="ICSDKNAME">
        <ICSDKNAME><xsl:value-of select="."/></ICSDKNAME>
    </xsl:template>

    <xsl:template match="ICSUKNAME">
        <ICSUKNAME><xsl:value-of select="."/></ICSUKNAME>
    </xsl:template>


    </xsl:stylesheet>

Is there a cleaner solution? What will happen with not defined elements? Will they disappear? Any suggestions? Thank you in advance!

4

1 回答 1

3

I would start by removing all whitespace-only text nodes

<xsl:strip-space elements="*"/>

Then have an identity template to copy everything from input to output unchanged (after the stripping of whitespace) unless otherwise specified

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

Now add specific templates for the elements you want to precede with a newline

<xsl:template match="ICSGROUP|ICSDKNAME|ICSUKNAME">
  <xsl:text>&#xa;</xsl:text>
  <xsl:call-template name="ident"/>
</xsl:template>

And a special one for LISTESTOF to add an extra newline before the closing tag

<xsl:template match="LISTESTOF">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
    <xsl:text>&#xa;</xsl:text>
  </xsl:copy>
</xsl:template>
于 2013-10-26T19:57:25.800 回答