Best practice for inserting and deleting elements via XSLT

dazraf

New Member
I am new to XSLT and now i have a rather complicated problem... My input file looks like\[code\]<?xml version="1.0" encoding="UTF-8" standalone="yes"?><doc> <outerElement> <first> <textElement>Some Text</textElement> </first> <second> <textElement>Some Text</textElement> </second> <third> <textElement>Some Text</textElement> </third> </outerElement></doc>\[/code\]The problem occurs with the "second" Element. In the input file it can have one of 3 forms:\[code\]MISSING<second> <textElement>Some Text</textElement></second><second missingCause="" />\[/code\]In the output file it should be inserted like the second form. If it was missing before the textElement should indicate it was inserted by the Template and whats important here is it has to be at the second position because i want to validate it against a xsd schema...Here is my current XSL:\[code\]<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output indent="yes"/> <xsl:strip-space elements="*"/> <!-- COPY ALL ELEMENTS --> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <!-- remove Elements with attribute deleteme --> <xsl:template match="outerElement/second[@missingCause='*']" /> <!-- look if second is there. If not insert --> <xsl:template match="outerElement"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> <xsl:if test="not(second)"> <second> </second> </xsl:if> </xsl:copy> </xsl:template> <!-- Insert Element second --> <xsl:template match="outerElement/second"> <xsl:apply-templates select="node()|@*"/> <xsl:copy> <xsl:if test="not(textElement)"> <textElement>Inserted by Template</textElement> </xsl:if> </xsl:copy> </xsl:template></xsl:stylesheet> \[/code\]If "second" is missing my output file just gets an Element "" but its empty and the last transformation does not get applied. Everything else looks fine while when i have in the Document i get a warning...Can someone please help me moving the Element to where it has to be so it is validates to a Schema and make it work in all three cases? I think my way seems not very good and will end up chaotic because i got several similar Elements to insert / delete like this.Thanks for reading ;)
 
Back
Top