To the best of my knowledge, XSL works as follows: it chooses some nodes to process via and then applies to each node in this selection.
I am confused because looks like here we have the same selection of SOMETHING twice: first in apply-template, and then in template match. Please consider my example below. I have got what I wanted: replaced the tags inside the Projects with PMatch tags only if the text attribute was not empty. But as you see, I have specified this condition twice! Is this a normal way?
XML
<?xml version="1.0" encoding="UTF-8"?>
<Manager text="this is a manager">
<Name text="true name">Ivan</Name>
<Projects text="ps">
<Project text="ba">Bank</Project>
<Project text="ca">Cars</Project>
<Project>Business</Project>
</Projects>
</Manager>
XSL
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:foo="myFoo" xmlns:xsl="http://ift.tt/tCZ8VR" xmlns:fo="http://ift.tt/vyPH5E" xmlns:xs="http://ift.tt/tphNwY" xmlns:fn="http://ift.tt/pEXiIz">
<xsl:output method="xml" encoding="UTF-8" indent="yes"/>
<xsl:template match="/Manager">
<ThisIsWhatIWantToSeeInName>
<xsl:apply-templates/>
</ThisIsWhatIWantToSeeInName>
</xsl:template>
<xsl:template match="Name">
<NewName>Rihanna</NewName>
</xsl:template>
<xsl:template match="Projects">
<Jobs>Jo-Jobs</Jobs>
<NewJobs>
<xsl:apply-templates select="Project[@text != '']"/>
</NewJobs>
</xsl:template>
<xsl:template match="Project[@text != '']">
<PMatch><xsl:value-of select="@text"/></PMatch>
</xsl:template>
</xsl:stylesheet>
Result:
<?xml version="1.0" encoding="UTF-8"?>
<ThisIsWhatIWantToSeeInName xmlns:fn="http://ift.tt/pEXiIz" xmlns:fo="http://ift.tt/vyPH5E" xmlns:foo="myFoo" xmlns:xs="http://ift.tt/tphNwY">
<NewName>Rihanna</NewName>
<Jobs>Jo-Jobs</Jobs>
<NewJobs>
<PMatch>ba</PMatch>
<PMatch>ca</PMatch>
</NewJobs>
</ThisIsWhatIWantToSeeInName>
To escape from double selection specification I tried the following:
1) I tried to make apply-template selection wider by selecting all the Proejcts. But when the template finds only those which have text attributes - others a send to default templates which results in some plain text in my XML. Can I affect this behaviour somehow? Can I turn off default templates?
2) I tried to limit the apply-template selection as much as I can. OK, but if I make now template match wider like match='/' (because all the correct node are selected in apply-templates) - my template wil match many elements before this part of code, it will match even the root node. May be, I can 'connect' somehow my template to the place where it is applied? I want to be sure that my template is called only where I want.
No comments:
Post a Comment