开发者

Change a single node's content in an element with XSL whilst copying the rest

I have some XML which features a fair number of attributes in each element, and sometimes I need to format one or two attributes if some condition is met. I thought I'd do this with XSL.

So inside my template in the XSL file I have the following:

<xsl:choose>
  <xsl:when test="ytd &lt; 0.000000001 or interest &lt; 0.000000001">
    <xsl:element name="Report">
      <xsl:choose>
        <xsl:when test="ytd&lt; 0.000000001">
          <xsl:element name="ytd">0</xsl:element>
        </xsl:when>
        <xsl:when test="interest &lt; 0.000000001">
          <xsl:element name="interest">0</xsl:element>
        </xsl:when>
        <xsl:otherwise>
          <xsl:copy-of select="." />
        </xsl:otherwise>
      </xsl:choose>
    </xsl:element>
  </xsl:when>
  <xsl:otherwise>
    <xsl:copy-of select="." />
  </xsl:otherwise>
</xsl:choose>

The operations for the YTD and interest fields work as I expect them to, essentially rounding down small amounts to zero for me. The problem is the otherwise clause; I seem to misunderstand how to use the copy-of. I want the other n attributes of a Report element to be copied over as they are in the original XML. Problem is with this current template I get output like the following for a Report which has a very small ytd:

<Report><ytd>0</ytd></Report>

So obviously I'm not copying the rest of the element properly. Any pointers?

EDIT: A sample input XML file might be:

<Reports>
  <Report>
    <name>Bob</name>
    <account>Saver</account>
    <ytd>100</ytd>
    <inte开发者_如何学Pythonrest>0.5</ytd>
    <cosigned>false</cosigned>
  </Report>
  <Report>
    <name>Steve</name>
    <account>Gold Account</account>
    <ytd>0.0000000001</ytd>
    <interest>0.0000000001</ytd>
    <cosigned>false</cosigned>
  </Report>
</Reports>

And desired output would be:

<Reports>
  <Report>
    <name>Bob</name>
    <account>Saver</account>
    <ytd>100</ytd>
    <interest>0.5</ytd>
    <cosigned>false</cosigned>
  </Report>
  <Report>
    <name>Steve</name>
    <account>Gold Account</account>
    <ytd>0</ytd>
    <interest>0</ytd>
    <cosigned>false</cosigned>
  </Report>
</Reports>

(Obviously I'm just mocking that up but hopefully you can see what I mean)

Thanks, Dave.


I think the easiest way to do what you want is:

<xsl:stylesheet 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

    <xsl:output method="xml" indent="yes"/>

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

    <xsl:template match="ytd[ . &lt; 0.000000001 ] | interest[ . &lt; 0.000000001]">
        <xsl:copy>0</xsl:copy>
    </xsl:template>

</xsl:stylesheet>
  • Use identity rule (see first template above) to copy everything as is
  • Override elements as required
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜