XSLT转文本:判断父节点最后子节点并添加分隔符/换行
Let's figure out what's going wrong here and fix it step by step:
Key Issues in Your Current XSLT
- Unmatched Namespace: Your XML has a default namespace
http://java.sun.com/xml/ns/jdbcon the<webRowSet>element, which means all child elements (data,currentRow,columnValue) belong to this namespace. But your XSLT doesn't declare or reference this namespace, so none of your template matches or node selections work—XSLT falls back to its default template, which just dumps all text content without any formatting. - Hardcoded Position Check: Using
$Rec_position=6to identify the last column is inflexible (it breaks if column counts change) and unnecessary. You should use dynamic position checks instead.
Fixed XSLT Code
<?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:jdbc="http://java.sun.com/xml/ns/jdbc"> <!-- Bind the XML's namespace --> <xsl:output method="text" omit-xml-declaration="yes" indent="no"/> <xsl:strip-space elements="*"/> <xsl:variable name="Delimiter" select="'|'"/> <xsl:variable name="NewLine" select="' '"/> <xsl:template match="/"> <!-- Output header row --> <xsl:text>EXPR5_5|VOUCHER_ID|INVOICE_ID|ENTERED_DT|GROSS_AMT|UnifierRecordNo</xsl:text> <xsl:value-of select="$NewLine"/> <xsl:apply-templates select="jdbc:webRowSet/jdbc:data"/> </xsl:template> <xsl:template match="jdbc:data"> <xsl:for-each select="jdbc:currentRow"> <xsl:for-each select="jdbc:columnValue"> <xsl:value-of select="."/> <!-- Add delimiter only if this isn't the last column in the row --> <xsl:if test="position() != last()"> <xsl:value-of select="$Delimiter"/> </xsl:if> </xsl:for-each> <!-- Add new line after each row --> <xsl:value-of select="$NewLine"/> </xsl:for-each> </xsl:template> </xsl:stylesheet>
What Changed & Why
- Namespace Binding: Added
xmlns:jdbc="http://java.sun.com/xml/ns/jdbc"to map the XML's namespace to a prefix. All node references now use this prefix (jdbc:currentRow,jdbc:columnValue) so XSLT can correctly target the elements. - Dynamic Position Check: Replaced the hardcoded
6withposition() != last(), which automatically detects if the current<columnValue>is the last one in its parent<currentRow>—this works regardless of how many columns you have. - Cleaner Variable Definitions: Simplified the delimiter and newline variables for readability.
- Explicit Node Selection: Directly target
jdbc:webRowSet/jdbc:datain the root template to avoid unnecessary template processing.
Expected Output
EXPR5_5|VOUCHER_ID|INVOICE_ID|ENTERED_DT|GROSS_AMT|UnifierRecordNo |26068384|070-0010055-4842MAR18|2018-04-25|170.310|UI-004058 |26068385|070-0010058-5739MAR18|2018-04-25|209.900|UI-004057
内容的提问来源于stack exchange,提问作者AC267
相关产品推荐
相关产品推荐

