XSLT,如何在转换过程中识别不同的模式?

时间:2016-05-10 17:39:42

标签: xslt

我有一个源xml,如下所示:

<root>
  <CompoundPredicate booleanOperator="surrogate">
    <CompoundPredicate booleanOperator="and">
      <True />
      <SimplePredicate field="MODELYEAR" operator="lessOrEqual" value="1999" />
    </CompoundPredicate>
    <False />
  </CompoundPredicate>

  <CompoundPredicate booleanOperator="surrogate">
    <CompoundPredicate booleanOperator="and">
      <True />
      <SimplePredicate field="MODELYEAR" operator="lessOrEqual" value="1999" />
    </CompoundPredicate>
    <SimplePredicate field="AGE" operator="lessOrEqual" value="40" />
    <False />
  </CompoundPredicate>
</root>

我想以这种方式进行转型 1)。如果只有&#39; False&#39;内在&#39; CompoundPredicate&#39;元素,然后删除外部&#39; CompoundPredicate&#39;元素和内在“复合预测”之后出现的元素。元件。例如,

<CompoundPredicate booleanOperator="surrogate">
   <CompoundPredicate booleanOperator="and">
     <True />
     <SimplePredicate field="MODELYEAR" operator="lessOrEqual" value="1999" />
   </CompoundPredicate>
   <False />
</CompoundPredicate>

变为

   <CompoundPredicate booleanOperator="and">
     <True />
     <SimplePredicate field="MODELYEAR" operator="lessOrEqual" value="1999" />
   </CompoundPredicate>

2)如果在内部&#39; CompoundPredicate&#39;之后还有其他元素。除了&#39; False&#39;以外的元素,然后只删除&#39; False&#39;内在&#39; CompoundPredicate&#39;之后出现的元素元件。例如,

  <CompoundPredicate booleanOperator="surrogate">
    <CompoundPredicate booleanOperator="and">
      <True />
      <SimplePredicate field="MODELYEAR" operator="lessOrEqual" value="1999" />
    </CompoundPredicate>
    <SimplePredicate field="AGE" operator="lessOrEqual" value="40" />
    <False />
  </CompoundPredicate>

变为

  <CompoundPredicate booleanOperator="surrogate">
    <CompoundPredicate booleanOperator="and">
      <True />
      <SimplePredicate field="MODELYEAR" operator="lessOrEqual" value="1999" />
    </CompoundPredicate>
    <SimplePredicate field="AGE" operator="lessOrEqual" value="40" />
  </CompoundPredicate>

对于这个问题,我甚至不知道如何开始。我将衷心感谢您的帮助。非常感谢。

1 个答案:

答案 0 :(得分:1)

看看这是否指向正确的方向。它基于对规则的重述,这可能是也可能不正确:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

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

<!-- for outer 'CompoundPredicate' that contains only inner 'CompoundPredicate' and/or 'False' -->
<xsl:template match="root/CompoundPredicate[not(*[not(self::CompoundPredicate or self::False)])]">
    <xsl:apply-templates select="CompoundPredicate"/>
</xsl:template>

<!-- remove 'False' elements, children of outer 'CompoundPredicate' -->
<xsl:template match="root/CompoundPredicate/False"/>

</xsl:stylesheet>