Mark
Mark

Reputation: 13

xpath - Predicate with attribute issue

I have a value which I am trying to trim down to 4 characters which is contained in an xml sub-element with the attribute WEIGHT.

  <addinfo>
    <info type="COMMODITY_CODE">39253000</info>
    <info type="WEIGHT">0.04700</info>
  </addinfo>

The full path is documents/invoice/detailline/addinfo/info type="WEIGHT"

My template says:

  <xsl:template match="documents/invoice/detailline/addinfo/info[@type='WEIGHT']">
<xsl:element name="{name()}" namespace="{namespace-uri()}">
  <xsl:value-of select="substring(.,  '0', '5')" />
</xsl:element>

It should be trimming the value 0.04700 down to a total of 4 characters (0.47). Instead it is doing this, but also eliminating the type attribute "WEIGHT".

Transform Output:

  <addinfo>
    <info type="COMMODITY_CODE">39253000</info>
    <info>0.04</info>
  </addinfo>

Upvotes: 1

Views: 125

Answers (1)

JLRishe
JLRishe

Reputation: 101778

It's doing exactly what you're asking it to do: creating an element with the same name, and putting the trimmed value in it. To include the type attribute in the result, you can make a copy of it:

<xsl:template match="documents/invoice/detailline/addinfo/info[@type='WEIGHT']">
  <xsl:element name="{name()}" namespace="{namespace-uri()}">
    <xsl:copy-of select="@*" />
    <xsl:value-of select="substring(., 1, 4)" />
  </xsl:element>
</xsl:template>

FYI, the numbering in substring() (and most other things in XPath) starts at 1, and the second and third parameters are numbers, not strings. I've fixed that above.

Upvotes: 2

Related Questions