簡體   English   中英

使用xslt 2.0基於xml注釋節點拆分節點

[英]split nodes based on xml comment nodes using xslt 2.0

我有一個需要一些XSLT轉換的XML文檔。 這是XML:

<docs>
  <!-comment->
  <doc>
     <node add="1"/>
     <node add="2"/>
     <!-comment->
     <node add="3"/>
     <node add="4"/>
     <node add="5"/>
     <!-comment->
     <node add="6"/>
     <node add="7"/>
     <node add="8"/>
  </doc>
</docs>

轉換后,以上結構應如下所示:

<docs>
  <!-comment->
  <doc>
     <node add="1"/>
     <node add="2"/>
  </doc>
  <!-comment->
  <doc>
     <node add="3"/>
     <node add="4"/>
     <node add="5"/>
  </doc>
  <!-comment->
  <doc>
     <node add="6"/>
     <node add="7"/>
     <node add="8"/>
  </doc>
</docs>

到目前為止,我的代碼是:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">

    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

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

    <xsl:template match="docs">
       <xsl:for-each select="comment">
            <doc>
             <xsl:copy-of select="following-sibling::node[not(following-sibling::comment)]"/>
            <doc>
       <xsl:for-each>
    </xsl:template>

這段代碼確實復制了節點,但是它復制了注釋后的所有節點(這是錯誤的)。 從結構上講,我可以說出我在做錯什么,但是我無法提出正確的模式來對節點進行分組並相應地放置它們。 同樣,節點數可以針對不同的XML進行更改。

針對這些情況,發明了XSLT元素xsl:for-each-group 有關更多信息,請參見https://www.saxonica.com/html/documentation/xsl-elements/for-each-group.html

我的解決方案:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="UTF-8" indent="yes"/>

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

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

<xsl:template match="doc">
    <xsl:for-each-group select="node|comment()" group-starting-with="comment()">
       <xsl:copy-of select="current-group()[self::comment()]"/>
       <doc>
          <xsl:copy-of select="current-group()[self::element()]"/>
       </doc>
    </xsl:for-each-group>
</xsl:template>

</xsl:stylesheet>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM