Altova Mailing List Archives>Archive Index >comp.text.xml Archive Home >Recent entries >Thread Prev - Best Way To Strip XML Document of Unwanted Nodes [Thread Next] Re: Best Way To Strip XML Document of Unwanted NodesTo: NULL Date: 10/5/2005 12:57:00 AM Eddy C wrote: > I'm trying to strip an XML document of unwanted nodes such that in the > example below I would keep all the parent nodes of a child node I > wanted and for other parents which do not have the child requested they > would be stripped. > > I understand I could use XSLT but I'm doing this in java and was > wondering if there was a preferred approach out there. > > > Before > <a> > <b> > <c>fdfdsf</c> > </b> > <b> > <x>dffsd</x> > </b> > <b> > <x>dffsd</x> > <c>fdfdsf</c> > </b> > </a> > > After requesting to keep child c > <a> > <b> > <c>fdfdsf</c> > </b> > <b> > <c>fdfdsf</c> > </b> > </a> XSLT is easier to use for this, IMHO: <?xml version="1.0" encoding="iso-8859-1"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml"/> <xsl:param name="keep"/> <xsl:template match="*"> <!-- check current element, descendants, and siblings --> <xsl:variable name="matches"> <xsl:for-each select=".|descendant::*|../*"> <xsl:if test="name()=$keep"> <xsl:text>Y</xsl:text> </xsl:if> </xsl:for-each> </xsl:variable> <xsl:if test="$matches!=''"> <xsl:copy> <xsl:apply-templates/> </xsl:copy> </xsl:if> </xsl:template> </xsl:stylesheet> There's probably a more elegant way, but my brain stopped working an hour ago. ///Peter | ||||||
| Company | Legal | Press | Partners | Careers | Sitemap | Contact Us | Altova Blog | Mobile | Full Site | |||
|
