Find all child with -optional- comment and remove them

Questions about XML that are not covered by the other forums should go here.
neat1
Posts: 2
Joined: Tue Aug 20, 2019 10:32 am

Find all child with -optional- comment and remove them

Post by neat1 » Tue Aug 20, 2019 10:41 am

Dear All,

I am trying to find and remove all children which has the optional part. Hence in this example, I would like to remove the descriptions.

<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>
<!--Optional:-->
Two of our famous Belgian Waffles with plenty of real maple syrup
</description>
<description2>
<!--Optional:-->
Only for lactose intolerants
<description2>
<calories>650</calories>
</food>

At the end, my desired outcome is this:
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<calories>650</calories>
</food>

Is this possible with oxygen somehow?

Best Regards,

Andrew

Radu
Posts: 6437
Joined: Fri Jul 09, 2004 5:18 pm

Re: Find all child with -optional- comment and remove them

Post by Radu » Tue Aug 20, 2019 11:52 am

Hi Andrew,

You need an XSLT stylesheet like this:

Code: Select all

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">
    <!-- Copy everything unchanged -->
    <xsl:template match="node() | @*">
        <xsl:copy>
            <xsl:apply-templates select="node() | @*"/>
        </xsl:copy>
    </xsl:template>
    
    <!-- Remove elements which contain the optional comment -->
    <xsl:template match="*[comment()[contains(., 'Optional:')]]"/>
</xsl:stylesheet>
The stylesheet can be applied either with a transformation scenario:

https://www.oxygenxml.com/doc/versions/ ... -xslt.html

or used from a custom XSLT-based refactoring operation which can be applied on multiple documents, something like this:

post54224.html

Regards,
Radu
Radu Coravu
<oXygen/> XML Editor
http://www.oxygenxml.com

neat1
Posts: 2
Joined: Tue Aug 20, 2019 10:32 am

Re: Find all child with -optional- comment and remove them

Post by neat1 » Tue Aug 20, 2019 12:18 pm

Thank you so much!!!!

Post Reply