对 XSLT 非常陌生!在记录之间添加新行时遇到困难



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

<?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>

我的肥皂 xml 输出如下

<?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 模板转换此 xml 输出时,我得到以下格式的记录

100200

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

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

我希望我的输出是这样的

Numbers|
100|
200|

您的样式表实际上没有执行任何操作,因为您唯一的模板与源 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>

最新更新