2014-12-04 88 views
1

分組XML元素更改XML結構我不得不重新組合基於所述屬性 我有這樣通過基於屬性

<a> 
    <b> 
     <c> 
      <d1 att2="t1">test 1</d1> 
      <d1>test 2</d1> 
      <d1>test 3</d1> 
      <d1 att2="t1">test 4</d1> 
     </c> 
    </b> 
</a> 

一個xml在相同的XML結構的XML元素我需要CONVER此xml到,

<a> 
    <b> 
     <c> 
      <d1 att2="t1">test 1</d1> 
      <d1 att2="t1">test 4</d1> 
     </c> 
    </b> 
</a> 
<a> 
    <b> 
     <c> 
      <d1>test 2</d1> 
     </c> 
    </b> 
</a> 
<a> 
    <b> 
     <c> 
      <d1>test 3</d1> 
     </c> 
    </b> 
</a> 
+0

確認,如果'att2'是相同的,然後將它們分組,但是如果它不同或丟失,那麼新的組?你有沒有使用xslt 2處理器?請標記這樣? – StuartLC 2014-12-04 18:16:33

+0

@StuartLC您的假設是正確的,我可以訪問xslt 2處理器。 – chavsh 2014-12-04 18:26:12

回答

0

這是一個真正沒有靈感/手動的努力,但似乎完成了工作。該模板將單獨分支應用於具有和不具有@att2屬性的元素。

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

    <xsl:template match="/"> 
     <root> 
      <xsl:for-each-group select="//d1[@att2]" group-by="@att2"> 
       <a> 
        <b> 
         <c> 
          <xsl:for-each select="current-group()"> 
           <xsl:apply-templates select="." mode="nowrapper"></xsl:apply-templates> 
          </xsl:for-each> 
         </c> 
        </b> 
       </a> 
      </xsl:for-each-group> 
      <xsl:apply-templates select="//d1[not(@att2)]" mode="wrapper" /> 
     </root> 
    </xsl:template> 

    <xsl:template match="d1" mode="wrapper"> 
     <a> 
      <b> 
       <c> 
        <xsl:apply-templates select="." mode="nowrapper" /> 
       </c> 
      </b> 
     </a> 
    </xsl:template> 

    <xsl:template match="d1" mode="nowrapper"> 
     <xsl:copy-of select="." /> 
    </xsl:template> 

</xsl:stylesheet> 
+0

感謝@StuartLC的幫助。 – chavsh 2014-12-04 20:29:23