I’ve just started learning XML & XSLT and have a quick question regarding Xpath.
Here’s the XML code:
<root>
<shop>
<person>
<employee>
<name> Alexis </name>
<role> Manager </role>
<task> Sales </task>
</employee>
</person>
</shop>
<person>
<employee>
<role> Supervisor </role>
<name> Blake </name>
<task> Control </task>
</employee>
</person>
</root>
and here’s the XSLT code:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="root">
<html><head></head>
<body><xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match="shop">
<xsl:apply-templates select="/root/*/*"/>
</xsl:template>
<xsl:template match="employee">
<u> <xsl:apply-templates select="name"/> </u>
(Task: <xsl:apply-templates select="task"/>)
<br></br>
</xsl:template>
<xsl:template match="person2">
<xsl:apply-templates />
</xsl:template>
</xsl:stylesheet>
The output is:
Alexis (Task: Sales )
Blake (Task: Control )
Blake (Task: Control )
What I don’t understand is why the last part is duplicated? I know that it’s due to this part of the XSLT code:
<xsl:apply-templates select="/root/*/*"/>
but that’s only because I was fiddling around with the code and displaying it in Firefox. I don’t understand why though.
From what I understand, it’s selecting all the grandchildren elements of “root”, like so:
root/shop/person
but why isn’t Alexis repeated as well? Only Blake is repeated…
In your root matching template, you do
<xsl:apply-templates/>which will pick the first shop and person elements. With respect to the person element, there isn’t a specific template for this, and so XSLT will continue to match its child elements and pick up the employee for ‘Blake’However, there is a matching template for shop and the issue is indeed with what you do in the template that matches it.
Because you have started the xpath expression with
/rootthis will start mathing relative to the root element of the document, and not the shop element you are currently positioned on. This means it will select the elements /root/shop/person and /root/person/employee which leads to your duplicate ‘Blake’. However, as you are not matching the employee element for ‘Alexis’ elsewhere, this is only output once.You probably need to do just this instead, to match the employee element
This will match all grand-children of the current element.
*will match the child element, and so*/*will match the child elements of the child elements.However, if the intent is to output just the employee elements, you can simplify your XSLT by taking advantage of the fact that the default template matching behaviour for an element is to process its child elements. Try this XSLT:
When applied to your XML, the following is output