0

I am trying to convert the value of XML element into some other format e.g KG to LBS. Let say I have a XML

<all>
    <one>Something 1</one>
    <two>something 2</two>
    <check>
        <present>true</present>
    </check>
    <action>
        <perform></perform>
    </action>
    <a>
        <Weight>1Kg</Weight>
    </a>
</all>

after XSLT my expected output is

<?xml version="1.0" encoding="UTF-8"?><all>
<one>Something 1</one>
<two>something 2</two>
<check>
<present>true</present>
</check>
<action>
<perform/>
</action>
<a>
<UNIT-WEIGHT>2.2046226218487757</UNIT-WEIGHT>
</a>
</all>

for this I write

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

<xsl:template match="Weight">
    <UNIT-WEIGHT>
      <xsl:value-of select=". div 0.45359237"/>
    </UNIT-WEIGHT>
    </xsl:template>

If <Weight>1</Weight> I get my desired output & if <Weight>1Kg</Weight> I get <UNIT-WEIGHT>NaN</UNIT-WEIGHT>

What I need to do ??

1
  • <xsl:value-of select="translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', '') div 0.45359237"/> try with this. Commented Aug 9, 2016 at 10:02

1 Answer 1

1

I would prefer to know what exactly can be the value of Weight before answering this. One or two examples do not disclose a rule.

Try perhaps:

<xsl:template match="Weight">
    <UNIT-WEIGHT>
        <xsl:value-of select="translate(., translate(., '.0123456789', ''), '') div 0.45359237"/>
    </UNIT-WEIGHT>
</xsl:template>

This will filter out all characters except digits and decimal point, which are necessary to construct a valid number (assuming a weight cannot be negative).

Note that this will fail with a value such as:

<Weight>1.5 kg.</Weight>

because 1.5. is not a valid number.

Sign up to request clarification or add additional context in comments.

2 Comments

Is there any logic that can be applicable which could be worked in <Weight>1.5kg</Weight>. . ??
@AnandDeshmukh The above will work perfectly well with <Weight>1.5kg</Weight>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.