Remove elements based on node

Questions about XML that are not covered by the other forums should go here.
neodjandre
Posts: 4
Joined: Sat Jul 22, 2017 1:26 pm

Remove elements based on node

Post by neodjandre »

My XML has the following structure:

Code: Select all

 <element>
<url></url>
<category></category>
<subcategory></subcategory>
<title></title>
<summary></summary>
<source>By Andrew</source>
<date>Feb 25, 2017</date>
<body></body>
<images></images>
</element>
I would like to delete all elements that do not have the content of the <source> node equal to "By Andrew".

How could I do this please?
Radu
Posts: 9049
Joined: Fri Jul 09, 2004 5:18 pm

Re: Remove elements based on node

Post by Radu »

Hi,

You can do something 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 -->
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:template>

<!-- Match elements which need to be filtered and do not copy them to the output -->
<xsl:template match="element[not(source/text() = 'By Andrew')]"/>
</xsl:stylesheet>
Regards,
Radu
Radu Coravu
<oXygen/> XML Editor
http://www.oxygenxml.com
neodjandre
Posts: 4
Joined: Sat Jul 22, 2017 1:26 pm

Re: Remove elements based on node

Post by neodjandre »

Hi Radu,

Many thanks for this but where should I place this code?
Radu
Posts: 9049
Joined: Fri Jul 09, 2004 5:18 pm

Re: Remove elements based on node

Post by Radu »

Hi,

You can use the Oxygen "File->New" dialog wizard to create a new XSLT stylesheet. Then for the XSLT stylesheet create a new transformation scenario using the "Configure Transformation Scenarios" toolbar button. Configure the transformation scenario by setting the path to the XML file and run it.

An easier alternative is to go to the Oxygen "Tools" menu->XML Refactoring->Delete element and as the element path set element[not(source/text() = 'By Andrew')].

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