2016-02-19 45 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)。 –