对XSLT来说很新!难以在记录之间添加新行

时间:2016-02-18 22:33:08

标签: xslt

我有一个soap xml输出,需要将其转换为纯文本文件。我正在尝试使用xsltproc。在线获得以下xsl tempalate

XName

我的soap xml输出如下

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:csv="csv:csv">
    <xsl:output method="text" encoding="utf-8" />
    <xsl:strip-space elements="*" />
    <xsl:variable name="delimiter" select="'|'" />

    <csv:columns><column>Numbers</column></csv:columns>

    <xsl:template match="getNumbersResponse">
        <xsl:variable name="property" select="." />

        <xsl:text>&#xa;</xsl:text>
    </xsl:template>

</xsl:stylesheet>

当我使用上面的xsl tempalate尝试xsltproc来转换这个xml输出时,我得到以下格式的记录

100200

我想在每条记录之间添加一个新行。在网上发现添加以下行应该这样做但我在xsl模板中看到输出中有或没有此行的任何更改。

<?xml version='1.0' encoding='utf-8'?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body>
<ns4:getNumbersResponse xmlns:ns4="http://service.engine.com"><ns4:Numbers>100</ns4:Numbers>
<ns4:Numbers>200</ns4:Numbers>
</ns4:getNumbersResponse>
</soapenv:Body>
</soapenv:Envelope>

我希望我的输出像这样

<xsl:text>&#xa;</xsl:text>

1 个答案:

答案 0 :(得分:1)

您的样式表实际上并没有做任何事情,因为您唯一的模板与源XML中的任何内容都不匹配。您看到的输出纯粹是内置模板规则的结果。

如果您想获得ns4:Numbers值的以返回分隔的列表,您应该这样做:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns4="http://service.engine.com">
<xsl:output method="text" encoding="utf-8" />

<xsl:template match="/soapenv:Envelope">
    <xsl:for-each select="soapenv:Body/ns4:getNumbersResponse/ns4:Numbers">
        <xsl:value-of select="."/>
        <xsl:if test="position()!=last()">
             <xsl:text>&#xa;</xsl:text>
        </xsl:if>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet> 

请注意使用声明的前缀来处理XML中的节点。

要在编辑过的问题中获得结果,请执行以下操作:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns4="http://service.engine.com">
<xsl:output method="text" encoding="utf-8" />

<xsl:template match="/soapenv:Envelope">
    <xsl:text>Numbers|&#xa;</xsl:text>
    <xsl:for-each select="soapenv:Body/ns4:getNumbersResponse/ns4:Numbers">
        <xsl:value-of select="."/>
        <xsl:text>|&#xa;</xsl:text>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>