0

我有这样的数据-

<item>
    <name>Bob</name>
    <fav_food>pizza</fav_food>
    <key>{Salary}</key>
    <value>1000</value>
</item>

我希望我的输出看起来像这样 -

<item>
    <name>Bob</name>
    <fav_food>pizza</fav_food>
    <Salary>1000</Salary>
</item>

编辑,而不仅仅是一个值,如果我有其他标签,只有一个标签保证像这样是非空的,那么我的转换有什么问题?我使用 Sean 的 XSLT 1.0 转换作为源。

输入 -

<item>
    <name>Bob</name>
    <fav_food>pizza</fav_food>
    <key>{Salary}</key>
    <value />
    <value2>1000</value2>
    <value3 />
</item>

所需的输出 -

<item>
    <name>Bob</name>
    <fav_food>pizza</fav_food>
    <Salary>1000</Salary>
</item>

我目前的转变 -

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" omit-xml-declaration="yes" />
<xsl:strip-space elements="*" />  

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

<xsl:template match="key">
<xsl:element name="{substring-before(substring-after(.,'{'),'}')}"> 
    <xsl:choose>
        <xsl:when test="value != ''">
            <xsl:value-of select="following-sibling::value" />
        </xsl:when>
        <xsl:when test="value2 != ''">
            <xsl:value-of select="following-sibling::value2" />
        </xsl:when>
        <xsl:when test="value3 != ''">
            <xsl:value-of select="following-sibling::value3" />
        </xsl:when>
        </xsl:choose>
    </xsl:element> 
</xsl:template>
</xsl:stylesheet>
4

1 回答 1

1

XSLT 1.0 解决方案...

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" omit-xml-declaration="yes" />
<xsl:strip-space elements="*" />  

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

<xsl:template match="value" />

<xsl:template match="key">
 <xsl:element name="{substring-before(substring-after(.,'{'),'}')}"> 
   <xsl:value-of select="following-sibling::value" /> 
 </xsl:element> 
</xsl:template>

</xsl:stylesheet>

更新

这里也是一个 XSLT 2 解决方案。这是未经测试的。

<xsl:stylesheet version="2.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:fn="http://www.w3.org/2005/xpath-functions">
<xsl:output indent="yes" omit-xml-declaration="yes" />
<xsl:strip-space elements="*" />  

<xsl:template match="element()">
  <xsl:copy>
    <xsl:apply-templates select="@*,node()"/>
   </xsl:copy>
</xsl:template>

<xsl:template match="attribute()|text()|comment()|processing-instruction()">
  <xsl:copy/>
</xsl:template>

<xsl:template match="value" />

<xsl:template match="key">
 <xsl:element name="{fn:replace(.,'^\{(.*)\}$','$1')}"> 
   <xsl:value-of select="following-sibling::value" /> 
 </xsl:element> 
</xsl:template>

</xsl:stylesheet>
于 2013-06-21T16:00:24.043 回答