1 2 3 The following ...">

Is it possible to match "none" in XSL?

Given the following XML snippet:

<foo>
  <bar>1</bar>
  <bar>2</bar>
  <bar>3</bar>
</foo>

The following XSL should work:

<xsl:template match="/">
  <xsl:apply-templates
    mode="items"
    select="bar" />
</xsl:template>

<xsl:template mode="items" match="bar">
  <xsl:value-of select="." />
</xsl:template>

Is there a way that I can use a similar format to apply the template if there are no objects <bar/>? For instance:

<xsl:template match="/">
  <xsl:apply-templates
    mode="items"
    select="bar" />
</xsl:template>

<xsl:template mode="items" match="bar">
  <xsl:value-of select="." />
</xsl:template>

<xsl:template mode="items" match="none()">
  There are no items.
</xsl:template>
+3
source share
4 answers

You can also use this template to avoid additional settings:

<xsl:template match="/*">
    <xsl:apply-templates select="bar" mode="items"/>
    <xsl:apply-templates select="(.)[not(bar)]" mode="show-absence-message"/>
</xsl:template>

<xsl:template match="bar" mode="items">
    <xsl:value-of select="."/>
</xsl:template>

<xsl:template match="/*" mode="show-absence-message">
    There are no items.
</xsl:template>
+2
source

Yes.

But the logic should be:

<xsl:template match="foo">
   <xsl:apply-templates select="bar"/>
</xsl:template>

<xsl:template match="foo[not(bar)]">
   There are no items. 
</xsl:template> 

Note: An item foothat has or does not have barchildren.

+5
source

, apply-templates select="bar", node bar, , . , , Apply, ,

  <xsl:choose>
     <xsl:when test="bar">
        <xsl:apply-templates select="bar"/>
     </xsl:when>
     <xsl:otherwise>There are not items.</xsl:otherwise>
  </xsl:choose>
+1

XML:

<foo>
    <bar>1</bar>
    <bar>2</bar>
    <bar>3</bar>
</foo>

The following XSL should work:

<xsl:template match="/">
 <xsl:apply-templates mode="items" select="bar" />
</xsl:template>

<xsl:template mode="items" match="bar">
 <xsl:value-of select="." />
</xsl:template>

No, the <xsl:apply-templates>above does not select node at all .

Is there a way that I can use a similar format for this to apply a template when there are no objects?

Yes

<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="/*[not(bar)]">
      No <bar/> s.
    </xsl:template>

    <xsl:template match="/*[bar]">
      <xsl:value-of select="count(bar)"/> <bar/> s.
    </xsl:template>
</xsl:stylesheet>

when applied to the provided XML document :

<foo>
    <bar>1</bar>
    <bar>2</bar>
    <bar>3</bar>
</foo>

result :

3<bar/> s.

When applied to this XML document :

<foo>
    <baz>1</baz>
    <baz>2</baz>
    <baz>3</baz>
</foo>

result :

  No <bar/> s.
0
source

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


All Articles