copying a tag to xml output based on a condition

Here should go questions about transforming XML with XSLT and FOP.
anboss
Posts: 8
Joined: Wed May 07, 2008 4:43 pm

copying a tag to xml output based on a condition

Post by anboss »

need help writing xsl for following problem:

the following will be input

<main>
<item>books</item>
<source>A</source>
<destination>B</destination>
<status>yes</status>
</main>

based on the values for source, destination and the text of shipQuery, present in the following xml (stored in c:\)... i will copy the status tag in output.

<shipQuery>
<item source='A' destination='B'>books</item>
<item source='Z' destination='default'>pen</item>
<item source='B' destination='A'>default</item>
</shipQuery>

here a default means dont care. (source/destination/item can be anything)

as we can see my output will be

<main>
<item>pen</item>
<source>A</source>
<destination>B</destination>
<status>yes</status>
</main>

if there is no match in the shipQuery xml,

<main>
<item>pen</item>
<source>A</source>
<destination>B</destination>
</main>

will be my output

how can this be achieved?
george
Site Admin
Posts: 2095
Joined: Thu Jan 09, 2003 2:58 pm

Re: copying a tag to xml output based on a condition

Post by george »

Hi,

The following stylesheet

Code: Select all


<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output indent="yes"/>
<xsl:template match="/">
<xsl:if test="not(document('shipQuery.xml')/shipQuery/item[
(@source=current()/main/source or @source='default') and
(@destination=current()/main/destination or @destination='default') and
(.=current()/main/item or .='default')
])">
<main>
<xsl:copy-of select="/main/item"/>
<xsl:copy-of select="/main/source"/>
<xsl:copy-of select="/main/destination"/>
</main>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
applied on a document like

Code: Select all


<main>
<item>pen</item>
<source>A</source>
<destination>B</destination>
<status>yes</status>
</main>
will give

Code: Select all


<?xml version="1.0" encoding="UTF-8"?>
<main>
<item>pen</item>
<source>A</source>
<destination>B</destination>
</main>
This assumes that there is a shipQuery.xml file in the same folder with the following content:

<shipQuery>
<item source='A' destination='B'>books</item>
<item source='Z' destination='default'>pen</item>
<item source='B' destination='A'>default</item>
</shipQuery>

Best Regards,
George
George Cristian Bina
Post Reply