Is it possible to detect the presence (xml) of a tag using XSLT?

I suppose to check for the tag and create a new node according to the result.

This is the input XML:

<root> 
  <tag1>NS</tag1> 
  <tag2 id="8">NS</tag2> 
  <test> 
    <other_tag>text</other_tag> 
    <main>Y</main> 
  </test> 
  <test> 
    <other_tag>text</other_tag> 
  </test> 
</root> 

And the required XML output:

<root> 
  <tag1>NS</tag1> 
  <tag2 id="8">NS</tag2> 
  <test> 
    <other_tag>text</other_tag> 
    <Main_Tag>Present</Main_Tag> 
  </test> 
  <test> 
    <other_tag>text</other_tag> 
    <Main_Tag>Absent</Main_Tag>
  </test> 
</root> 

I know to check the value of the tag, but this is something new for me.

I tried using this template: (which does not work as per requirement)

   <xsl:template match="test"> 
      <xsl:element name="test"> 
        <xsl:for-each select="/root/test/*"> 
      <xsl:choose> 
        <xsl:when test="name()='bbb'"> 
          <xsl:element name="Main_Tag"> 
            <xsl:text>Present</xsl:text> 
          </xsl:element> 
        </xsl:when> 
        <xsl:otherwise> 
          <xsl:element name="Main_Tag"> 
          <xsl:text>Absent</xsl:text> 
          </xsl:element> 
        </xsl:otherwise> 
      </xsl:choose> 
        </xsl:for-each> 
      </xsl:element> 
  </xsl:template> 
+3
source share
4 answers

, - , , , , - , . , , . , :

<xsl:template match="test/main">
   <Main_Tag>present</Main_Tag>
</xsl:template>

<xsl:template match="test[not(main)]">
   <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
      <Main_Tag>absent</Main_Tag>
   </xsl:copy>
</xsl:copy>
+1

:

<xsl:choose>
    <xsl:when test="main = 'Y'">
        <Main_Tag>Present</Main_Tag> 
    </xsl:when>
    <xsl:otherwise>
        <Main_Tag>Absent</Main_Tag>
    </xsl:otherwise>
</xsl:choose>

<Main_Tag>
    <xsl:choose>
        <xsl:when test="main = 'Y'">Present</xsl:when>
        <xsl:otherwise>Absent</xsl:otherwise>
    </xsl:choose>
</Main_Tag>
+5

...

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <!--Identity transform-->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>   

    <!--Add <Main_Tag>Present</Main_Tag> or <Main_Tag>Absent</Main_Tag>.-->
    <xsl:template match="test">
        <xsl:copy>
           <xsl:apply-templates select="@*|node()"/>
           <Main_Tag>
                <xsl:choose>
                    <xsl:when test="main = 'Y'">Present</xsl:when>
                    <xsl:otherwise>Absent</xsl:otherwise>
                </xsl:choose>
            </Main_Tag>
        </xsl:copy>
    </xsl:template>

     <!--Remove all <main> tags-->
    <xsl:template match="main"/>       
</xsl:stylesheet>
+1

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


All Articles