如何用XSLT将层级元素拼接为字符串?TYPE_CU等元素问题求助
Hey there! Let's work through this together. Since you didn't share your exact XML source or desired output, I'll use a common scenario to show how to handle TYPE_CU and ID_CU elements—especially filtering for the "IV" value in TYPE_CU—while using concat() correctly in XSLT.
First, let's define a sample XML source
Let's say your input looks like this, with records that have different TYPE_CU values:
<Root> <Customer> <TYPE_CU>IV</TYPE_CU> <ID_CU>CU-789</ID_CU> <Name>Alice Smith</Name> </Customer> <Customer> <TYPE_CU>XX</TYPE_CU> <ID_CU>CU-101</ID_CU> <Name>Bob Jones</Name> </Customer> <Customer> <TYPE_CU>IV</TYPE_CU> <ID_CU>CU-456</ID_CU> <Name>Charlie Brown</Name> </Customer> </Root>
Let's say your desired output is a text list of IV-type customers
Like this:
IV Customer: CU-789 - Alice Smith IV Customer: CU-456 - Charlie Brown
Here's the XSLT code to achieve this
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" encoding="UTF-8"/> <!-- Match the root element --> <xsl:template match="/"> <!-- Loop only through Customer elements where TYPE_CU equals "IV" --> <xsl:for-each select="Root/Customer[TYPE_CU='IV']"> <!-- Use concat() to combine the values into a single string --> <xsl:value-of select="concat('IV Customer: ', ID_CU, ' - ', Name)"/> <!-- Add a newline after each entry --> <xsl:text> </xsl:text> </xsl:for-each> </xsl:template> </xsl:stylesheet>
Common issues you might be hitting
Let's troubleshoot the problems you mentioned with TYPE_CU and ID_CU:
- Incorrect context path: If you're trying to access
TYPE_CUorID_CUfrom the wrong context (e.g., not inside the parent element that contains them), theconcat()function will return empty strings for those values. Always make sure yourselectpath correctly targets the parent node first (likeRoot/Customerin the example) before accessing child elements. - Missing or optional elements: If some records don't have
TYPE_CUorID_CU,concat()will just include empty space for those parts. To handle this, you can use conditional logic:<xsl:value-of select="concat( 'IV Customer: ', if (ID_CU) then ID_CU else 'No ID', ' - ', Name )"/> - Case sensitivity: If your XML has
type_cu(lowercase) instead ofTYPE_CU, or the value is "iv" instead of "IV", your filter won't match. Usetranslate()to ignore case if needed:<xsl:for-each select="Root/Customer[translate(TYPE_CU, 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')='IV']">
If your actual XML structure or desired output is different, feel free to share those details, and we can adjust the code accordingly!
内容的提问来源于stack exchange,提问作者Martin Migota
相关产品推荐
相关产品推荐

