I have following XML file – with a Book Name and respective Authors. The Authors can be 1 or more in counts for the same Book –
<Authors>
<book>
<bName>HTML5</bName>
<AName>John</AName>
<AName>James</AName>
<AName>Jack</AName>
</book>
<book>
<bName>Java</bName>
<AName>Joe</AName>
</book>
<book>
<bName>XML</bName>
<AName>John</AName>
<AName>James</AName>
</book>
....
</Authors>
Using XSLT, how can I generate output as,
<p>
<b>HTML5</b/><br/>
John, James and Jack
</p>
<p>
<b>Java</b/><br/>
Joe
</p>
<p>
<b>XML</b/><br/>
John and James
</p>
In short, if there are more than 1 authors then separated by comma and an “and” between the last and last but one author name.
I am using XSLT 1.0. If not possible with 1.0, then can it be done with 2.0..?
Thanks in advance and have a nice day – John
One way to do this is to have various matching templates for the AName elements.
AName elements which must be followed by a comma must have 2 or more following AName elements:
Other AName elements which have a following AName element which are not picked up by the first match, must then need an “and” amd not a comma, after them.
All other AName elements with be the last in the list, and so have nothing following.
So, given the following XSLT
When applied to the following XML
The following HTML is output
Do note the order of the matching templates in the XSLT is important. The most specific case has to come after the more general case.