开发者

xslt substring question

I am new to XSLT. I have a input XML file which needs to be shown as a different output XML. I am using the xslt for transformation. Input XML:

<Row>
<Column>abc.xyz.ijm</Column>
<Row>

Output XML:

<abc>
  <xyz>
    <ijm>String</ijm>
  </xyz>
</abc>

I tried using xsl:when along with substring-before and substring-after functions but the result xml is not close to what I want. How to know the last occurence of '.' so that <ijm>String</ijm> is constructed 开发者_Python百科followed by the end tags of the words that are found before each of the previous occurences of the '.' so that </xyz> and </abc> can be added as shown in the output xml above?

Any code snippet is not at all appreciated.

Thanks in advance.


This transformation:

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

 <xsl:template match="Column/text()" name="tokenize">
   <xsl:param name="pText" select="."/>
   <xsl:if test="string-length()">
    <xsl:choose>
      <xsl:when test="not(contains($pText,'.'))">
        <xsl:element name="{$pText}">String</xsl:element>
      </xsl:when>
      <xsl:otherwise>
        <xsl:element name="{substring-before($pText,'.')}">
          <xsl:call-template name="tokenize">
            <xsl:with-param name="pText"
              select="substring-after($pText,'.')"/>
          </xsl:call-template>
        </xsl:element>
      </xsl:otherwise>
    </xsl:choose>
   </xsl:if>
 </xsl:template>
</xsl:stylesheet>

when applied on the provided XML document (corrected to be well-formed):

<Row>
    <Column>abc.xyz.ijm</Column>
</Row>

produces the wanted, correct result:

<abc>
   <xyz>
      <ijm>String</ijm>
   </xyz>
</abc>

Explanation:

  1. Recursively called named template with stop condition: the $pText parameter is either the empty string or a string that doesn't contain the period character.

  2. Intermediate action: Create an element whose name is the substring-before the '.' character, then call yourself recursively with the text after the first period character as parameter.

  3. Stop action: Create an element with name -- the whole string in the parameter, and value: the string "String".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜