How to fine tune the value of an XML element using XSLT

I am trying to convert the value of an XML element to another format, such as KG, in LBS. Say I have 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 result

<?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 result, and if <Weight>1Kg</Weight>, I get<UNIT-WEIGHT>NaN</UNIT-WEIGHT>

What should I do?

0
source share
1 answer

I would rather know what exactly can be a value Weightbefore answering this. One or two examples do not reveal the rules.

Try maybe:

<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 build a valid number (provided that the weight cannot be negative).

, , :

<Weight>1.5 kg.</Weight>

1.5. .

+1

Source: https://habr.com/ru/post/1662242/


All Articles