I have several information entries that I want to separate with a comma. However, each entry could be empty, and if the first-appearing entry is empty, then comma should not appear. For example:
if we have four XSLT parameters: name, phone number, address, occupation
and we have
- Name: John
- Phone number: 111-111-1111
- Address: Imaginary street
- Occupation: Baker
Then final string should be:
John, 111-111-1111, Imaginary street, Baker
if the name and phone number parameters were empty or null, then final string should be:
Imaginary street, Baker
if only phone number null or empty, then final string should be:
John, Imaginary street, Baker
In a language like C#, I would write the code like this:
foreach (EntryObject entry in entryList)
{
if (firstEntry == true && entry.Type != EntryType.Age && entry.Type != EntryType.Sex)
{
finalString += entry.ValueString;
firstEntry = false;
}
else if (firstEntry == false && entry.Type != EntryType.Age && entry.Type != EntryType.Sex)
{
finalString += ", " + entry.ValueString;
}
}
return finalString;
However, I heard that variables in XSLT are immutable. How should I approach this problem in XSLT?
Edit:
The xml entry would look something like this:
<AddressBook>
<PersonalInfo>
<Age>33</Age>
<Sex>Male</Sex>
<Name>John</Name>
<PhoneNumber></PhoneNumber>
<Address>Imaginary Street</Address>
<Occupation>Baker</Occupation>
</PersonalInfo>
</AddressBook>
Note that certain entries could be empty, and I will only use name, phonenumber, address and occupation. Age and Sex should be ignored.
Use an XPath condition that matches only the non-empy elements (
string-length(.)>0or simplystring(.)), and then use theposition()function to check if an element is the first or not. Input XML:XSLT:
where the first template is the one actually doing the work,
<xsl:template match="text()">removes the text contained in unmatched elements (by default XSLT processor would copy such text to the output) and<xsl:template match="root">generates the root element of the output document.Result:
If you are interested in only some of the fields you just select them using the union operator (
|) – e.g. if you want only phone, address and occupation in the example above modify the XSLT to be: