使用xslt 2.0解析BBCode

时间:2009-12-08 22:45:12

标签: xslt parsing bbcode

我需要帮助找到一个可行的解决方案来将bbcode转换为html,这是我到目前为止的地方,但是当bbcodes被包装时失败。

的Src:

 [quote id="ohoh81"]asdasda
     [quote id="ohoh80"]adsad
         [quote id="ohoh79"]asdad[/quote]
     [/quote]
 [/quote]

代码:

<xsl:variable name="rules">
    <code check="&#xD;" >&lt;br/&gt;</code>
    <code check="\&#91;(quote)(.*)\&#93;" >&lt;span class=&#34;quote&#34;&gt;</code>
</xsl:variable>

<xsl:template match="text()" mode="BBCODE">
  <xsl:call-template name="REPLACE_EM_ALL">
    <xsl:with-param name="text" select="." />
    <xsl:with-param name="pos" select="number(1)" />
  </xsl:call-template>
</xsl:template>

<xsl:template name="REPLACE_EM_ALL">
  <xsl:param name="text" />
  <xsl:param name="pos" />
  <xsl:variable name="newText" select="replace($text, ($rules/code[$pos]/@check), ($rules/code[$pos]))" />
  <xsl:choose>
    <xsl:when test="$rules/code[$pos +1]">
      <xsl:call-template name="REPLACE_EM_ALL">
        <xsl:with-param name="text" select="$newText" />
        <xsl:with-param name="pos" select="$pos+1" />
      </xsl:call-template>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of disable-output-escaping="yes" select="$newText" />
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

2 个答案:

答案 0 :(得分:2)

我认为一种更可行的方法是重复匹配和替换(通过正则表达式)的BBcode标签,直到你没有匹配。例如。对于[quote][url]

<xsl:function name="my:bbcode-to-xhtml" as="node()*">
  <xsl:param name="bbcode" as="xs:string"/> 
  <xsl:analyze-string select="$bbcode" regex="(\[quote\](.*)\[/quote\])|(\[url=(.*?)\](.*)\[/url\])" flags="s">
    <xsl:matching-substring>
      <xsl:choose>
        <xsl:when test="regex-group(1)"> <!-- [quote] -->
          <span class="quote">
            <xsl:value-of select="my:bbcode-to-xhtml(regex-group(2))"/>
          </span>
        </xsl:when>
        <xsl:when test="regex-group(3)"> <!-- [url] -->
          <a href="regex-group(4)">
            <xsl:value-of select="my:bbcode-to-xhtml(regex-group(5))"/>
          </a>
        </xsl:when>
      </xsl:choose>
    </xsl:matching-substring>
    <xsl:non-matching-substring>
      <xsl:value-of select="."/>
    </xsl:non-matching-substring>
  </xsl:analyze-string>
</xsl:function>

答案 1 :(得分:1)

这可能是一个坏主意,因为XSLT旨在处理格式良好的XML,而不是任意文本。我建议你首先预先处理BBCode,用<>替换左右括号,做任何你需要的东西,使它成为格式良好的XML,然后用XSL处理它。