2016-02-19 39 views
0

我使用下面的XSLT省略XML樹的某些部分,而排序使用XSLT

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

<xsl:output method="xml" omit-xml-declaration="no" encoding="UTF-8" indent="yes" /> 
<xsl:strip-space elements="*"/> 

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

<xsl:template match="*[*]"> 
    <xsl:copy> 
     <xsl:apply-templates> 
      <xsl:sort select="local-name()"/> 
     </xsl:apply-templates> 
    </xsl:copy> 
</xsl:template> 
</xsl:transform> 

的問題是排序一個大的XML文件,我想省略XML的某些子樹。我不知道我怎麼能做到這一點。例如,可以說我的原始XML是

<Car> 
    <Handling> 
     <Suspension> 
      <Type>Coilover</Type> 
      <Brand>Ohlins</Brand> 
     </Suspension> 
     <Steering> 
      <Type>Electric</Type> 
      <Brand>Momo</Brand> 
     </Steering> 
    </Handling> 
    <Engine> 
     <Hybrid> 
      <Type>LiON</Type> 
      <Brand>Duracell</Brand> 
     </Hybrid> 
     <Combustion> 
      <Type>Rotary</Type> 
      <Brand>Mazda</Brand> 
     </Combustion> 
    </Engine> 
</Car> 

輸出應該如下所示。請注意,在<Handling>下的所有內容都沒有排序

<Car> 
    <Engine> 
     <Combustion> 
      <Brand>Mazda</Brand> 
      <Type>Rotary</Type> 
     </Combustion> 
     <Hybrid> 
      <Brand>Duracell</Brand> 
      <Type>LiON</Type> 
     </Hybrid> 
    </Engine> 
    <Handling> 
     <Suspension> 
      <Type>Coilover</Type> 
      <Brand>Ohlins</Brand> 
     </Suspension> 
     <Steering> 
      <Type>Electric</Type> 
      <Brand>Momo</Brand> 
     </Steering> 
    </Handling> 
</Car> 

任何想法如何通過修改XSLT來實現這一點?

回答

2

樣式表中有兩個模板,一個只複製上下文節點,另一個複製上下文節點並對其子元素進行排序。

要從排序機制中排除某些元素,您需要排除它們不被第二個模板處理。一種可能(快速劈)解決方案是添加另一種模板匹配Handling及其所有後代,做一個正常的拷貝:

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

工程。謝謝 – BrownTownCoder

+0

關於它的「駭人聽聞的事情」是你明確地設置了高優先級。將已有的排序模板修改爲'>'可能會更好,因爲我已經告訴OP [here]( http://stackoverflow.com/a/35491574/1987598)。 –