简体   繁体   English

使用xslt将字符转换为xml节点

[英]convert characters to xml node using xslt

<xsl:variable name="string" select="'abcdefghijklmnopqrstuvwxyz'" />

I would need to convert this string to a node, grouped by 5 characters, obviously the last group can be less than or equal to 5 characters depending on the input string 我需要将此字符串转换为一个节点,该节点按5个字符分组,显然最后一组可以小于或等于5个字符,具体取决于输入字符串

<node>
  <a>abcde</a>
  <a>fghij</a>
  <a>klmno</a>
  <a>pqrst</a>
  <a>uvwxy</a>
  <a>z</a>
</node>

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:param name="pStr" select="'abcdefghijklmnopqrstuvwxyz'" />
 <xsl:param name="pChunkSize" select="5"/>

 <xsl:template match="/*">
  <node>
    <xsl:call-template name="split"/>
  </node>
 </xsl:template>

 <xsl:template name="split">
  <xsl:param name="pStr" select="$pStr" />
  <xsl:param name="pChunkSize" select="$pChunkSize"/>

  <xsl:variable name="pRemLength" select="string-length($pStr)"/>

  <xsl:if test="$pRemLength">
   <a><xsl:value-of select="substring($pStr, 1, $pChunkSize)"/></a>

   <xsl:call-template name="split">
    <xsl:with-param name="pStr" select="substring($pStr, $pChunkSize+1)"/>
    <xsl:with-param name="pChunkSize" select="$pChunkSize"/>
   </xsl:call-template>
  </xsl:if>

 </xsl:template>
</xsl:stylesheet>

when applied on any XML document (not used), produces the wanted, correct result : 当应用于任何XML文档(未使用)时,会产生所需的正确结果

<node>
   <a>abcde</a>
   <a>fghij</a>
   <a>klmno</a>
   <a>pqrst</a>
   <a>uvwxy</a>
   <a>z</a>
</node>

Explanation : Primitive recursion with no string length as the stop condition, and with each recursion step producing the next chunk and cutting it from the string. 说明 :没有字符串长度的原始递归作为停止条件,并且每个递归步骤都会生成下一个块并将其从字符串中剪切掉。

这是一个带有答案的类似问题,您可以轻松地将其更改以涵盖您的问题: http : //www.jguru.com/faq/view.jsp?EID=1070072

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM