Is it possible to detect the presence of a (xml) tag using XSLT?
I am suppose to test the presence of a 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>
<ma开发者_运维问答in>Y</main>
</test>
<test>
<other_tag>text</other_tag>
</test>
</root>
And the required output XML is :
<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 test the value of the tag, but this is something new to me.
I tried using this Template : (which is not working as per the 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>
What about just this:
<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>
Or
<Main_Tag>
<xsl:choose>
<xsl:when test="main = 'Y'">Present</xsl:when>
<xsl:otherwise>Absent</xsl:otherwise>
</xsl:choose>
</Main_Tag>
I'm not suggesting this is superior - for this problem, I'd probably do it exactly the way Rubens Farias describes - but it shows another approach to the problem which might be useful in more complex situations. I find that the more logic I push into template-matching, the more flexible and extensible my transforms turn out to be in the long run. So, add these to the identity transform:
<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>
You can use the Xpath count function to see if the main
node exists (count(name) = 0
) and output accordingly.
Expanding on Rubens Farias' second answer...
<?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>
精彩评论