I am working on XSLT, where I need to implement something as follows. My Source XML sample looks like this.
<?xml version="1.0" encoding="ISO-8859-1"?>
<catalog>
<cd>
<title>A</title>
<title>B</title>
<title>C</title>
</cd>
</catalog>
Consider there is some key value pair list is there.
Key Value
A Algebra
B Biology
C Chemistry
D Data Analysis
--- ---
---- ---
I need to write an xslt such that for every occurance of key 'A', need to replace with appropriate value.
I also need to mention the list of Key value pairs in the same XSLT. Sample Output:
<Data>
<Subject>Algebra</Subject>
<Subject>Biology</Subject>
<Subject>Chemistry</Subject>
</Data>
Can any one help me out how to do it.
Thank you.
I. Simple XSLT 1.0 Solution
This transformation:
when applied on the provided XML document:
produces the wanted, correct result:
Explanation:
This is the standard way of including inline XML node as a global element (child element of
xsl:stylesheet
) that belongs to a (non-empty) namespace, different than the xsl namespace.II. More efficient XSLT 1.0 solution, using keys:
when this transformation is applied on the same XML document (above), the same correct, wanted result is produced:
Explanation:
Accessing data via the
key()
function is typically sub-linear -- often O(1) and is extremely faster than linear search (which is important if the number of nodes to be searched is big).Accessing a node of one document via an index (
xsl:key
) while processing a node of another document is possible if the document containing the node to be looked-up is the current document. To access nodes from the other document, its root (or node of interest need to be saved and referenced off a variable.)III. XSLT 2.0 solution:
when this transformation is applied on the same XML document (above), the same correct, wanted result is produced:
Explanation:
Almost the same as the efficient XSLT 1.0 solution, but:
In XSLT 2.0 a template match pattern can contain a variable reference.
In XSLT 2.0 there is no need for acrobatic tricks manipulating the current and the indexed documents -- the 3rd argument of the
key()
function is to specify the tree whose index to use.