Home. 
.

transparent

transparent

transparent

Altova Mailing List Archives


Re: Best Way To Strip XML Document of Unwanted Nodes

From: Peter Flynn <peter.nosp@-.--------.-->
To: 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



transparent
Print
Mail
Like It
Disclaimer
.

These Archives are provided for informational purposes only and have been generated directly from the Altova mailing list archive system and are comprised of the lists set forth on www.altova.com/list/index.html. Therefore, Altova does not warrant or guarantee the accuracy, reliability, completeness, usefulness, non-infringement of intellectual property rights, or quality of any content on the Altova Mailing List Archive(s), regardless of who originates that content. You expressly understand and agree that you bear all risks associated with using or relying on that content. Altova will not be liable or responsible in any way for any content posted including, but not limited to, any errors or omissions in content, or for any losses or damage of any kind incurred as a result of the use of or reliance on any content. This disclaimer and limitation on liability is in addition to the disclaimers and limitations contained in the Website Terms of Use and elsewhere on the site.

.
.

transparent

transparent