xslt xsl:分析字符串和正则表达式

ati*_*tif 3 xslt

我有一个 xml 文件,我必须在其中查找模式并在匹配的特定模式周围放置一个“标记。

<xml>
<foo>
    <id>1</id>
    <description>This is section 1, this is section 1 or 2, this is section 1 and 2</description>
</foo>
</xml>
Run Code Online (Sandbox Code Playgroud)

现在在文件中我必须找到一个模式“section 1”,“section 1 or 2”和“section 1 and 2”,并在匹配的单词周围放置一个“标记。

我写了一个xslt,如下所示:

  <xsl:template match="text()">

<xsl:analyze-string select="." regex="section\s\d+|section\s\d+\s+or\s+\d|section\s\d+\s+and\s+\d">
  <xsl:matching-substring>
    <xsl:if test="matches(.,'section\s\d+')" >
      <xsl:text>"</xsl:text>
      <xsl:value-of select="."/>     
      <xsl:text>"</xsl:text>       
    </xsl:if>
    <xsl:if test="matches(.,'section\s\d+\s+or\s+\d')" >
      <xsl:text>"</xsl:text>
      <xsl:value-of select="."/>     
        <xsl:text>"</xsl:text>       
    </xsl:if>
    <xsl:if test="matches(.,'section\s\d+\s+and\s+\d')" >
      <xsl:text>"</xsl:text>
      <xsl:value-of select="."/>     
      <xsl:text>"</xsl:text>       
    </xsl:if>
  </xsl:matching-substring>
  <xsl:non-matching-substring>
    <xsl:value-of select="current()"/>
  </xsl:non-matching-substring>
</xsl:analyze-string>
 </xsl:template>
Run Code Online (Sandbox Code Playgroud)

我在这里面临的问题是模式“第 1 节”也匹配所有其他模式,所以我没有得到想要的结果

上述变换结果为

<xml>
  <foo>
      <id>1</id>
      <description>This is "section 1", this is "section 1" or 2, this is "section 1" and 2</description>
  </foo>
</xml>
Run Code Online (Sandbox Code Playgroud)

我想要这个输出。

<xml>
  <foo>
    <id>1</id>
    <description>This is "section 1", this is "section 1 or 2", this is "section 1 and 2"</description>
   </foo>
</xml>
Run Code Online (Sandbox Code Playgroud)

任何如何实施它的想法......并获得期望的结果。

谢谢。

Dav*_*sle 5

这似乎适用于您的输入:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

 <xsl:template match="*">
  <xsl:copy>
   <xsl:apply-templates/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="text()">
  <xsl:analyze-string select="." regex="section\s+\d+(\s+(or|and)\s+\d+)?">
   <xsl:matching-substring>
     <xsl:text>"</xsl:text>
     <xsl:value-of select="."/>     
     <xsl:text>"</xsl:text>       
   </xsl:matching-substring>
   <xsl:non-matching-substring>
    <xsl:value-of select="current()"/>
   </xsl:non-matching-substring>
  </xsl:analyze-string>
 </xsl:template>

</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

尽管如果您只是生成字符串而不是元素,xsl:anayze-string但超出了您的需要,并且这会产生相同的结果:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

 <xsl:template match="*">
  <xsl:copy>
   <xsl:apply-templates/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="text()">
  <xsl:value-of  select="replace(.,'section\s+\d+(\s+(or|and)\s+\d+)?','&quot;$0&quot;')"/>
 </xsl:template>

</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)