首页 > 解决方案 > 如何避免文件末尾的新行 - xml to csv through xslt

问题描述

我正在尝试将以下 xml 的 xml 转换为 csv。输入xml的结构如下所示。我的 xslt 没有在新行中打印第二个“标题”。

在我的 XSLT 中,我使用了 for-each 并使用 if 条件来检查它是否是最后一个节点,但它正在考虑单个块的最后一个节点,而不是整个 xml 文件的最后一个节点。在现有的 xslt 中需要调整什么?

<?xml version="1.0" encoding="UTF-8"?>
        <document>
            <businessobjects>
                <entry>
                    <HeaderLine>
                        <HeaderRow>H</HeaderRow>
                        <HeaderBusinessUnit>BU1</HeaderBusinessUnit>
                    </HeaderLine>
                    <LineDetails>
                        <Line>L</Line>
                        <Amount>100.00</Amount>   
                    </LineDetails>
                </entry>
                <entry>
                    <HeaderLine>
                        <HeaderRow>H</HeaderRow>
                        <HeaderBusinessUnit>BU2</HeaderBusinessUnit>
                    </HeaderLine>
                    <LineDetails>
                        <Line>L</Line>
                        <Amount>200.00</Amount>   
                    </LineDetails>
                </entry>
            </businessobjects>
        </document>
    
    Expected Output
    ===============
    H|BU1
    L|100.00
    H|BU2
    L|200.00
    
    XSLT
    ====
    <?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" omit-xml-declaration="yes"/>
    <xsl:strip-space elements="*"/>
    <xsl:variable name="newline" select="'&#10;'"/>
    
    
    <xsl:template match="/">
        <xsl:apply-templates select="//entry"/>
    </xsl:template>
    
    <xsl:template match="entry">
        <xsl:for-each select="HeaderLine">
            <xsl:value-of select="concat(HeaderRow,'|',HeaderBusinessUnit,$newline)"/>
        </xsl:for-each>
        <xsl:for-each select="LineDetails">
            <xsl:if test="position()!=last()">
                <xsl:value-of select="concat(Line,'|',Amount,$newline)"/>
            </xsl:if>
            <xsl:if test="position()=last()">
                <xsl:value-of select="concat(Line,'|',Amount)"/>    
            </xsl:if>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

Output with above xslt
======================
H|BU1
L|100.00H|BU2
L|200.00

标签: xmlxslttext

解决方案


<xsl:if test="position()!=last()">
               <xsl:value-of select="$newline"/>
           </xsl:if>
           <xsl:if test="position()=last()"/>
       </xsl:for-each>
    </xsl:template>
    
</xsl:stylesheet>

Adding the above lines towards the end of the xslt solved the issue.

推荐阅读