Selecting all text nodes in between two processing instructions with XPATH

后端 未结 1 1132
面向向阳花
面向向阳花 2021-01-28 02:21

I have some following XML:


  

test test test

相关标签:
1条回答
  • 2021-01-28 03:20

    I recommend using xal:for-each-group as suggested in the first comment by Maring Honnen. The other XPath approaches allow you to select the content between two processing instructions, but it will be hard to embed that in an xslt stylesheet that should do other things as well, like copying existing structure at the same time. Here a minimal approach using for-each-group:

    xquery version "1.0-ml";
    
    let $xml :=
      <content>
        <p>
          before
          <?change-addition-start?>
          test 
          <em>test</em>
          <strong>test</strong>
          <?change-addition-end?>
          after
        </p>
      </content>
    
    let $xsl :=
      <xsl:stylesheet version="2.0"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
        <xsl:template match="@*|node()" mode="#all">
          <xsl:copy>
            <xsl:apply-templates select="@*|node()" mode="#current"/>
          </xsl:copy>
        </xsl:template>
    
        <xsl:template match="*[processing-instruction()]">
          <xsl:variable name="parent" select="." />
    
          <xsl:for-each-group select="node()" group-starting-with="processing-instruction()">
            <xsl:choose>
              <xsl:when test="self::processing-instruction('change-addition-start')">
                <ins>
                  <xsl:apply-templates select="current-group()" mode="identity"/>
                </ins>
              </xsl:when>
    
              <xsl:otherwise>
                <xsl:apply-templates select="current-group()" mode="identity"/>
              </xsl:otherwise>
            </xsl:choose>
          </xsl:for-each-group>
        </xsl:template>
    
      </xsl:stylesheet>
    
    return xdmp:xslt-eval($xsl, $xml)
    

    Use a second for-each-group with group-ending-by as suggested by Martin if you like to get the end PI inside the <ins> tag. The above might be sufficient though.

    HTH!

    0 讨论(0)
提交回复
热议问题