2017-05-04 95 views
0

我有一個扁平的xml,我需要複製一個元素下的所有匹配元素。在一個組元素下複製匹配元素

在輸入xml中有標題元素可以隨機出現在xml中。我想把它們放在一個元素下面。任何幫助?

輸入:

<root> 
    <element> 
     <para>Text 11.</para> 
     <para>Text 22.</para> 
    </element> 
    <title number="1"> 
     <title.block>Title1</title.block> 
     <para>Text 33.</para> 
     <para>Text 44.</para> 
    </title> 
    <title number="2"> 
     <title.block>Title2</title.block> 
    </title> 
    <element1> 
     <para>Some Text</para> 
    </element1> 
    <title number="3"> 
     <title.block>Title2</title.block> 
     <para>Text 55.</para> 
    </title> 
    <result> 
     <para>Some Text</para> 
    </result> 
</root> 

期望的輸出是:

<root> 
    <element> 
     <para>Text 11.</para> 
     <para>Text 22.</para> 
    </element> 
    <title.group> 
    <title number="1"> 
     <title.block>Title1</title.block> 
     <para>Text 33.</para> 
     <para>Text 44.</para> 
    </title> 
    <title number="2"> 
     <title.block>Title2</title.block> 
    </title> 
    <title number="3"> 
     <title.block>Title2</title.block> 
     <para>Text 55.</para> 
    </title> 
    </title.group> 
    <element1> 
     <para>Some Text</para> 
    </element1> 
    <result> 
     <para>Some Text</para> 
    </result> 
</root> 
+1

如果您包含迄今爲止已嘗試的代碼並說出它做錯了什麼,那麼您更有可能獲得幫助。請參閱http://stackoverflow.com/help/how-to-ask。 – BPS

+0

我們不是「做我的家庭作業」服務。 – sergiol

+0

對不起。我嘗試了不同的XPath組合,但沒有爲我工作,所以不知道在這裏添加哪一個。但下次會記住。謝謝 – user23

回答

0

只需寫創建該組並複製該標題和所有下面的兄弟姐妹到該組的第一title模板:

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

    <xsl:output indent="yes"/> 

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

    <xsl:template match="root/title[1]">   
     <title-group> 
      <xsl:copy-of select="., following-sibling::title"/> 
     </title-group> 
    </xsl:template> 

    <xsl:template match="root/title[position() gt 1]"/> 

</xsl:transform> 

http://xsltransform.net/a9Giwu