2016-12-29 105 views
0

我有以下XML文件:XML元素排序

<?xml version="1.0" encoding="UTF-8"?> 
     <table> 
      <row> 
       <description2>ABC</description2> 
      </row> 
      <row> 
       <description2>DEF</description2> 
      </row> 
      <row> 
       <description2>GHI</description2> 
      </row> 
      <row> 
       <description1>JKL</description1> 
       <message>msg1</message> 
      </row> 
      <row> 
       <description1>MNO</description1> 
       <message>msg2</message> 
      </row> 
     </table> 

我想包含其中包含描述

所以行節點後顯示描述2子節點的所有行節點我生成的XML如下所示:

<?xml version="1.0" encoding="UTF-8"?> 
<table> 
    <row> 
     <description1>JKL</description1> 
     <message>msg1</message> 
    </row> 
    <row> 
     <description1>MNO</description1> 
     <message>msg2</message> 
    </row> 
    <row> 
     <description2>ABC</description2> 
    </row> 
    <row> 
     <description2>DEF</description2> 
    </row> 
    <row> 
     <description2>GHI</description2> 
    </row> 
</table> 

我該如何實現i n XSLT?

+0

您是否可以編輯您的問題以顯示您嘗試過的XSLT?謝謝。 –

+0

@Tim C嗨,我不知道XSLT。如果你能遵守我的要求,請幫助我。謝謝 。 – Sanjay

+0

@TimC嗨,我不知道XSLT。如果你能遵守我的要求,請幫助我。謝謝 。 – Sanjay

回答

0

嘗試這樣:

<?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" version="1.0" encoding="UTF-8" indent="yes"/> 

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

    <xsl:template match="table"> 
     <xsl:apply-templates select="row/description1/.."/> 
     <xsl:apply-templates select="row/description2/.."/> 
    </xsl:template> 
</xsl:stylesheet> 

注意目標元素是如何在第二個模板中選擇:

  • row - 尋子row元素,
  • description1 - 找到description1元素(兒童特別是row),
  • .. - 往上一級,找到包含剛剛找到的description1元素的行,並返回這些行。

然後有類似的選擇description2(實際上 - 包含這些description2元素的行)。

另一個解決方案,具有真正的排序,特別是如果您的源XML包含description標籤終止與其他數字有用。

替換爲第二模板:

<xsl:template match="table"> 
    <xsl:for-each select="row"> 
     <xsl:sort select="*[1]/name()" /> 
     <xsl:sort select="*[1]" /> 
     <xsl:copy> 
      <xsl:apply-templates select="node()|@*"/> 
     </xsl:copy> 
    </xsl:for-each> 
</xsl:template> 

第一次排序的關鍵是這裏的第一個孩子標籤(description...)和第二的名字 - 它的價值。

如果您不需要此功能,只需刪除第二條sort指令。