我有一个XML:
<?xml version="1.0" encoding="UTF-8"?>
<COLLECTION>
<Added>
<part>
<weight>5kg</weight>
</part>
<part>
<weight></weight>
</part>
<part>
<weight>2kg</weight>
</part>
</Added>
<Update>
<part>
<weight></weight>
</part>
<part>
<weight>3kg</weight>
</part>
<part>
<weight>2kg</weight>
</part>
</Update>
</COLLECTION>
我想在其上应用XSL,以便<weight>
标记需要转换为Weight
并考虑唯一的数字。这样我想添加一些额外的标记,这在输入XML中不存在。 <unitWeights>
如果<weight>
的价值仅为止,只有当它显示KG休息时才会为空。
预期产出:
<?xml version="1.0" encoding="UTF-8"?>
<COLLECTION>
<Added>
<part>
<Weight>5</Weight>
<unitWeights>KG</unitWeights>
</part>
<part>
<Weight></Weight>
<unitWeights></unitWeights>
</part>
<part>
<Weight>2</Weight>
<unitWeights>KG</unitWeights>
</part>
</Added>
<Update>
<part>
<Weight></Weight>
<unitWeights></unitWeights>
</part>
<part>
<Weight>3</Weight>
<unitWeights>KG</unitWeights>
</part>
<part>
<Weight>2</Weight>
<unitWeights>KG</unitWeights>
</part>
</Update>
</COLLECTION>
为此我申请了:
<xsl:template match="Weight">
<weight>
<xsl:value-of select="translate(.,translate(., '0123456789', ''), '')"/>
</weight>
</xsl:template>
<xsl:template match="WeightUnits">
<unitWeights>KG</unitWeights>
</xsl:template>
请帮我解决我错的地方。
答案 0 :(得分:1)
以下是满足您要求的通用解决方案。
对于只有'权重'的节点,您需要处理或应用模板。
<xsl:template match="weight">
然后您需要应用此处提到的translate
来仅提取字符串部分和仅提取数字部分。
XPath - extract numeric value out of string
为您演示:http://xsltransform.net/ejivdHb/23
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ns1="http://locomotive/bypass/docx" >
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="node()">
<xsl:copy>
<xsl:apply-templates select="node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="weight">
<xsl:variable name="currentWeight" select="translate(.,translate(., '0123456789', ''), '')" />
<xsl:variable name="currentWeightUnit" select="translate(., '0123456789', '')" />
<xsl:if test="string-length($currentWeight) > 0">
<Weight>
<xsl:value-of select="$currentWeight"/>
</Weight>
<xsl:if test="string-length($currentWeightUnit) > 0">
<unitWeights>
<xsl:value-of select="$currentWeightUnit"/>
</unitWeights>
</xsl:if>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
答案 1 :(得分:0)
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="weight">
<Weight>
<xsl:copy-of select="substring-before(.,'kg')"/>
</Weight>
<unitWeights>
<xsl:copy-of select="substring(., string-length(.) - 1)"/>
</unitWeights>
</xsl:template>
<xsl:template match="unitWeights"/>
</xsl:stylesheet>