'ReturnTrue if node is found
I need to form new element if specific node is found, but if that specific node is present several times i need to form only one element, My code is forming the aifound element twice.
<root>
<ai>
<i></i>
</ai>
<ai>
<i></i>
</ai>
</root>
output xml
<root>
<ai>
<i></i>
</ai>
<ai>
<i></i>
</ai>
<aifound>True</aifound>
</root>
My xslt
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="ai">
<aifound>True</aifound>
</xsl:template>
</xsl:stylesheet>
Solution 1:[1]
Not clear whether you want to add aifound if there are no ais at all. The following xslt adds aifound only if ais exist.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="@*|node()">
<xsl:copy-of select="."/>
</xsl:template>
<xsl:template match="root">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
<xsl:if test="//ai">
<aifound>True</aifound>
</xsl:if>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Solution 2:[2]
How about simply:
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="*"/>
<xsl:template match="/root">
<xsl:copy>
<xsl:copy-of select="*"/>
<aifound>
<xsl:value-of select="boolean(ai)"/>
</aifound>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pavel Koryakin |
| Solution 2 | michael.hor257k |
