I have created a stylesheet that is supposed to selectively copy the contents of an XML document so that I can strip out data that we do not need. I have provided 2 examples below and the stylesheet that we are currently using to do this. The stylesheet works, but I think there is probably a better way of doing it because in the current version I check for the same thing in two different locations (author='John Doe').
The rules for including an xml element in the output is as follows:
- If there is a notepad element within notepads that has the author text equal to 'John Doe' then include the notepads element in the output
- If the notepad element has an author element with text equal to 'John Doe' then include all elements within the notepad element in the xml output.
Input Example #1
<transaction>
<policy>
<insco>CC</insco>
<notepads>
<notepad>
<author>Andy</author>
<notepad>
<notepad>
<author>John Doe</author>
<notepad>
<notepad>
<author>Barney</author>
<notepad>
</notepads>
</policy>
</transaction>
Expected result for Input #1
<transaction>
<policy>
<insco>CC</insco>
<notepads>
<notepad>
<author>John Doe</author>
<notepad>
</notepads>
</policy>
</transaction>
Input Example #2
<transaction>
<policy>
<insco>CC</insco>
<notepads>
<notepad>
<author>Andy</author>
<notepad>
</notepads>
</policy>
</transaction>
Expected Result for Input #2
<transaction>
<policy>
<insco>CC</insco>
</policy>
</transaction>
Current Version of Stylesheet
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0" xmlns:fn="http://www.w3.org/2005/xpath-functions" exclude-result-prefixes="fn">
<xsl:template match="*">
<xsl:choose>
<xsl:when test="name()='notepads'">
<xsl:if test="/transaction/policy/insco='CC' and (notepad/author='John Doe')">
<xsl:copy>
<xsl:apply-templates />
</xsl:copy>
</xsl:if>
</xsl:when>
<xsl:when test="name()='notepad'">
<xsl:if test="author='John Doe'">
<xsl:copy>
<xsl:apply-templates />
</xsl:copy>
</xsl:if>
</xsl:when>
<xsl:otherwise>
<xsl:copy>
<xsl:apply-templates />
</xsl:copy>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>