How should I use the XSLT if statement correctly?

I created an XSLT stylesheet that looks for node and removes it. This works great. Now I want to check if any node exists, and then remove the node, if any.

So, I tried to add an if statement, and I ran into the following error:

Compilation error: dt.xls line file 10-element template element template
is allowed only as a child of the stylesheet

I think I understand the error, but I'm not sure how to get around it.

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

  <xsl:output omit-xml-declaration="yes" indent="yes"/>

  <xsl:template match="Ad">
    <xsl:template match="node()|@*">

      <xsl:if test="name-ad-size">
        <xsl:copy>
          <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
      </xsl:if>

    </xsl:template>
  </xsl:template>


  <xsl:template match="phy-ad-width"/>
  <xsl:strip-space elements="*"/>
  <xsl:preserve-space elements="codeListing sampleOutput"/>
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>
+3
source share
1 answer

, , XSLT, , , , #, Java, PHP. , , . XSLT , , , .

xsl:if . . , , . - :

<!-- starting point -->
<xsl:template match="/">
    <xsl:apply-templates select="root/something" />
</xsl:template>

<xsl:template match="name-ad-size">
   <!-- don't do anything, continue processing the rest of the document -->
   <xsl:apply-templates select="node() | @*" />
</xsl:template>

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

? , node . node <name-ad-size> - , , . , "catch all".

1: , <xsl:template> . <xsl:stylesheet> .

2: <xsl:template> . , , , ( ).


EDIT: - . :

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

  <xsl:output omit-xml-declaration="yes" indent="yes"/>
  <xsl:strip-space elements="*"/>
  <xsl:preserve-space elements="codeListing sampleOutput"/>

  <!-- NOTE: it is better to have a starting point explicitly -->
  <xsl:template match="/">
    <xsl:apply-templates select="root/something" />
  </xsl:template>

  <!-- I assume now that you meant to delete the <Ad> elements -->
  <xsl:template match="Ad">
     <xsl:apply-templates select="node()|@*"/>
  </xsl:template>

  <!-- NOTE: here you were already deleting <phy-ad-width> and everything underneath it -->
  <xsl:template match="phy-ad-width"/>

  <!-- NOTE: copies everything that has no matching rule elsewhere -->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>
+5

Source: https://habr.com/ru/post/1758041/


All Articles