xml+xsl中分割字符

来源:互联网 发布:娱乐圈乱 知乎匿名 编辑:程序博客网 时间:2024/04/29 12:16

    前几天,论坛上有一问题(详见:http://community.csdn.net/Expert/topic/3237/3237160.xml?temp=.6712152)

    解决这个问题,其实主要应用xpath中的两个function:substring-before;substring-after

具体例子如下:

    test.xml:

   <?xml version="1.0" encoding="UTF-8"?>
    <data_info CC_ID='195,196,197,198'/>

   -----------------------------------------------------------------------

   test.xsl:

   <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" method="xml" encoding="utf-8"/>
<xsl:template match="/data_info">
<xsl:element name="{name()}">
 <xsl:call-template name="splitStr">
   <xsl:with-param name="str" select="@CC_ID"/>
   <xsl:with-param name="ctrlname" select="'CC_ID'"/>
  </xsl:call-template>
</xsl:element>
</xsl:template>
<xsl:template name="splitStr">
 <xsl:param name="str"/>
 <xsl:param name="ctrlname"/>
  <xsl:element name="input">
   <xsl:attribute name="name"><xsl:value-of select="$ctrlname"/></xsl:attribute>
   <xsl:attribute name="value">
    <xsl:choose>
     <xsl:when test="contains($str,',')"><xsl:value-of select="substring-before($str,',')"/></xsl:when>
     <xsl:otherwise ><xsl:value-of select="$str"/></xsl:otherwise>
    </xsl:choose>
   </xsl:attribute>
  </xsl:element>
  <xsl:if test="contains($str,',')">
  <xsl:call-template name="splitStr">
   <xsl:with-param name="str" select="substring-after($str,',')"/>
   <xsl:with-param name="ctrlname" select="$ctrlname"/>
  </xsl:call-template>
 </xsl:if>
</xsl:template>
</xsl:stylesheet>

  --------------------------------------------------------------------------------

  转换后结果:

   <?xml version="1.0" encoding="utf-8"?>
<data_info>
<input name="CC_ID" value="195" />
<input name="CC_ID" value="196" />
<input name="CC_ID" value="197" />
<input name="CC_ID" value="198" />
</data_info>

原创粉丝点击