2

ハイフンで区切られた単語を見つけて、タグで囲むことはできますか?

入力

<root>
    text text text-with-hyphen text text    
</root>

必要な出力

<outroot>
    text text <sometag>text-with-hyphen</sometag> text text
</outroot>
4

2 に答える 2

3

This XSLT 2.0 transformation:

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

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

 <xsl:template match="root/text()">
  <xsl:analyze-string select="." regex="([^ ]*\-[^ ]*)+">
   <xsl:matching-substring>
     <sometag><xsl:value-of select="."/></sometag>
   </xsl:matching-substring>
   <xsl:non-matching-substring>
     <xsl:value-of select="."/>
   </xsl:non-matching-substring>
  </xsl:analyze-string>
 </xsl:template>
</xsl:stylesheet>

when applied on the provided XML document:

<root>
    text text text-with-hyphen text text
</root>

produces the wanted, correct result:

<root>
    text text <sometag>text-with-hyphen</sometag> text text
</root>

Explanation:

Proper use of the XSLT 2.0 <xsl:analyze-string> instruction and its allowed children-instructions.

于 2012-06-13T13:20:10.153 に答える
2

確認したところ、動作します。したがって、背後にあるアイデアは、テキスト全体に対して再帰的な反復を作成することです。XPath 関数を使用した再帰ステップ内でcontains、単語 (の使用法を参照$word) にハイフンが含まれているかどうかを検出します。

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/root">
        <outroot>
            <xsl:call-template name="split-by-space">
                <xsl:with-param name="str" select="text()"/>
            </xsl:call-template>
        </outroot>
    </xsl:template>
    <xsl:template name="split-by-space"> <!-- mode allows distinguish another tag 'step'-->
        <xsl:param name="str"/>
        <xsl:if test="string-length($str)"><!-- declare condition of recursion exit-->
        <xsl:variable name="word"> <!-- select next word -->
            <xsl:value-of select="substring-before($str, ' ')"/>
        </xsl:variable>
        <xsl:choose>
            <xsl:when test="contains($word, '-')"> <!-- when word contains hyphen -->
                <sometag>
                <xsl:value-of select='concat(" ", $word)'/><!-- need add space-->
                </sometag>
            </xsl:when>
            <xsl:otherwise>
                <!-- produce normal output -->
                <xsl:value-of select='concat(" ", $word)'/><!-- need add space-->
            </xsl:otherwise>
        </xsl:choose>
        <!-- enter to recursion to proceed rest of str-->
        <xsl:call-template name="split-by-space">
            <xsl:with-param name="str"><xsl:value-of select="substring-after($str, ' ')"/></xsl:with-param>
        </xsl:call-template>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>
于 2012-06-13T13:36:36.107 に答える