XSLT removing children from parent dynamically -
to avoid having hard code child element names want remove, i'd make dynamic process remove child elements when matching parent element name found.
my xml file:
<a> <b1> <c>c</c> <d>d</d> <e>e</e> <h>h</h> <mod> <c>c</c> <d>d</d> <e>e</e> <f>f</f> <g>g</g> </mod> </b1> <b2> <c>c</c> <e>e</e> <h>h</h> <mod> <c>c</c> <d>d</d> <e>e</e> <f>f</f> <g>g</g> </mod> </b2> <b3> <d>d</d> <e>e</e> <h>h</h> <x>x</x> <mod> <c>c</c> <d>d</d> <e>e</e> <f>f</f> <g>g</g> <x>g</x> </mod> </b3> </a>
desired output:
my xml file:
<a> <b1> <c>c</c> <d>d</d> <e>e</e> <h>h</h> <mod> <f>f</f> <g>g</g> </mod> </b1> <b2> <c>c</c> <e>e</e> <h>h</h> <mod> <d>d</d> <f>f</f> <g>g</g> </mod> </b2> <b3> <d>d</d> <e>e</e> <h>h</h> <x>x</x> <mod> <c>c</c> <f>f</f> <g>g</g> </mod> </b3> </a>
my xslt
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform" xmlns:xs="http://www.w3.org/2001/xmlschema" exclude-result-prefixes="xs"> <xsl:strip-space elements="*"/> <!-- copy nodes --> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <!-- remove child elements keep parent element same name --> <xsl:template match="c[../ancestor::*/c]"/> <xsl:template match="d[../ancestor::*/d]"/> <xsl:template match="e[../ancestor::*/e]"/> </xsl:stylesheet>
i think can combine remove element code this
<xsl:template match="c|d|e[../ancestor::*/c|d|e]"/>
i'm not sure how start, i'm thinking process have parent node names (c,d,e,h), cycle through children comparing parent node name each child node name. when match found, remove child element. thanks.
as far can tell, stylesheet need. produces output matching need excluding elements have parent preceding sibling of same name.
<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform" > <xsl:strip-space elements="*"/> <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/> <xsl:template match="*"> <xsl:if test="not(parent::*/preceding-sibling::*[name() = name(current())])"> <xsl:copy> <xsl:apply-templates/> </xsl:copy> </xsl:if> </xsl:template> </xsl:stylesheet>
Comments
Post a Comment