How to sub string the value of XML element using X

2019-09-10 04:19发布

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 ??

标签: xml xslt
1条回答
时光不老,我们不散
2楼-- · 2019-09-10 04:39

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.

查看更多
登录 后发表回答