基于XPath值在XSLT中动态生成字符串的解决方案求助
Got it, here's a clean, straightforward XSLT solution tailored to your requirement. It checks each of your XPath conditions and builds the concatenated string only for those that evaluate to 'Y':
XSLT 2.0+ Version (Recommended for Simplicity)
This version leverages sequences and the string-join function, which makes the logic concise and easy to maintain:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:us="your-us-namespace-uri" xmlns:ws="your-ws-namespace-uri"> <xsl:template match="/"> <!-- Collect roles where the corresponding condition is 'Y' into a sequence --> <xsl:variable name="roles" as="xs:string*"> <xsl:if test="us:user/ws:Additional_Information/ws:is_HR = 'Y'">HR</xsl:if> <xsl:if test="us:user/ws:Additional_Information/ws:is_Manager = 'Y'">Manager</xsl:if> <xsl:if test="us:user/ws:Additional_Information/ws:is_Employee = 'Y'">Employee</xsl:if> <xsl:if test="us:user/ws:Additional_Information/ws:is_Admin = 'Y'">Admin</xsl:if> </xsl:variable> <!-- Join the sequence with hyphens to form the final string --> <xsl:value-of select="string-join($roles, '-')"/> </xsl:template> </xsl:stylesheet>
How it works:
- Each
<xsl:if>checks if the corresponding XPath returns 'Y' — if yes, it adds the matching role name to a sequence. string-jointhen combines all elements in the sequence with hyphens. If all conditions are met, it outputsHR-Manager-Employee-Admin; if only, say,is_HRandis_Adminare 'Y', it outputsHR-Admin.
XSLT 1.0 Version (For Legacy Environments)
If you're stuck with XSLT 1.0 (which lacks sequences and string-join), here's a compatible alternative:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:us="your-us-namespace-uri" xmlns:ws="your-ws-namespace-uri"> <xsl:template match="/"> <!-- Store each condition result as a boolean variable --> <xsl:variable name="is-hr" select="us:user/ws:Additional_Information/ws:is_HR = 'Y'"/> <xsl:variable name="is-manager" select="us:user/ws:Additional_Information/ws:is_Manager = 'Y'"/> <xsl:variable name="is-employee" select="us:user/ws:Additional_Information/ws:is_Employee = 'Y'"/> <xsl:variable name="is-admin" select="us:user/ws:Additional_Information/ws:is_Admin = 'Y'"/> <!-- Build a string with hyphen-prefixed roles --> <xsl:variable name="raw-role-string"> <xsl:if test="$is-hr">-HR</xsl:if> <xsl:if test="$is-manager">-Manager</xsl:if> <xsl:if test="$is-employee">-Employee</xsl:if> <xsl:if test="$is-admin">-Admin</xsl:if> </xsl:variable> <!-- Remove the leading hyphen (if any) to get the final result --> <xsl:value-of select="substring($raw-role-string, 2)"/> </xsl:template> </xsl:stylesheet>
Note:
Don't forget to replace your-us-namespace-uri and your-ws-namespace-uri with the actual namespace URIs used in your XML input.
内容的提问来源于stack exchange,提问作者redyabkees
相关产品推荐
相关产品推荐

