If an XML file contains one tag that is used multiple times but in different context each time, it becomes a bit difficult extract and use each value programatically. In C# for instance, we could loop through the rows assigning values to variables but the same doesn’t hold true for XML (basically in stylesheet of xml with extension .xsl, which is used for generating report of xml file). The for-each loop concept does exist in XML stylesheet but it wouldn’t help as the loop would return the value of the last row only.
The following code is a section of the xml file:
<telecom value="tel:+1-444-555-6666" use="HP"/> ------> Home phone
<telecom value="tel:+1-888-999-2222" use="MC"/> ----->Mobile phone
<telecom value="mailto:email@example.com"/> ---->Email
As can be seen in the above code, the same <telecom> tag is used for different phone numbers (HP- Home Phone, MC- Moblile Phone) as well as for email too. So if we used for-each loop to extract the value, the email would be returned every time as it is the value in the last row.
To extract phone number from the telecom tag use the simple path,
But before that we have to check if the attibute i.e “use” is present or not. this can be done using the If conditional statement.
So, the full code for this is :
<xsl:if test="patient/telecom[@use]"> ---> checking whether the attribute is present or absent
<xsl:value-of select="patient/telecom/@value"/> ---> get the value of telecom tag i.e phone number
In the above example the tag in the XML file is used once but if the tag is repeated more than one times or if the parent element may be different means instead pf patient/telecom, if we have person/telecom or student/telecom or physician/telecom etc. then instead of writing four times (for patient, person, student, physician) we create one function and pass that value and change the path in select clause. Here in xsl file the function is called as template.
<xsl:call-template name="getTelecom"> --->Call the getTelecom function
<xsl:with-param name="telecom" select="patient/telecom[@use]"/>
The following code for template calling.
<xsl:with-param name="telecom" select="patient/telecom"/>
To use the email address see the code below:
<xsl:variable name="telecomPrefix" select="substring(.,1,7)"></xsl:variable>
<xsl:if test="$telecomPrefix = 'mailto:'">