如何在 XSLT 中将 XML 数据转换为 CSV 格式

How to Convert XML Data into CSV format in XSLT

我的xml输入如下

<?xml version="1.0" encoding="UTF-8" ?>
<EmployeeRequest xmlns="http://www.example.org"
   <EmployeeDetails>
     <FirstName>Khan</FirstName>
     <LastName>Joshi</LastName>
     <Age>30</Age>
   </EmployeeDetails>
   <EmployeeDetails>
     <FirstName>Josh</FirstName>
     <LastName>Luis</LastName>
     <Age>29</Age>
   </EmployeeDetails>
</EmployeeRequest> 

但我的输出应该如下所示。

FirstName, LastName, Age
Khan, joshi,30
Josh,Luis,29

这里EmployeeDetails是Unbound.Using模板怎么解决?

请告诉我如何获得此输出

路径//*[not(*)]给你所有的叶子元素(因为你似乎对根EmployeeRequest和容器EmployeeDetails不感兴趣),然后<xsl:value-of select="//*[not(*)]/name()" separator=", "/> 将输出名称。假定 XSLT 2.0 处理器。

如果你想让它保持通用,你可以使用

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

<xsl:output method="text"/>

<xsl:template match="/">
    <xsl:value-of select="/*/*[1]/*/local-name()" separator=", "/>
    <xsl:text>&#10;</xsl:text>
    <xsl:apply-templates select="/*/*"/>
</xsl:template>

<xsl:template match="*/*">
    <xsl:if test="position() > 1">
        <xsl:text>&#10;</xsl:text>
    </xsl:if>
    <xsl:value-of select="*" separator=", "/>
</xsl:template>

</xsl:transform>

参见 http://xsltransform.net/gWmuiK1 示例。

这是一个纯 XSLT 1.0 解决方案:

<xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:e="http://www.example.org">

<xsl:output method="text"/>

<xsl:template match="/">
    <xsl:apply-templates select="//e:EmployeeDetails[1]" mode="heading"/>
    <xsl:apply-templates select="//e:EmployeeDetails"/>
</xsl:template>

<xsl:template match="e:EmployeeDetails" mode="heading">
    <xsl:for-each select="*">
        <xsl:value-of select="local-name()"/>
        <xsl:call-template name="comma"/>
    </xsl:for-each>
    <xsl:text>&#10;</xsl:text>
</xsl:template>

<xsl:template match="e:EmployeeDetails">
    <xsl:for-each select="*">
        <xsl:value-of select="text()"/>
        <xsl:call-template name="comma"/>
    </xsl:for-each>
    <xsl:text>&#10;</xsl:text>
</xsl:template>

<xsl:template name="comma">
    <xsl:if test="position() != last()">,</xsl:if>
</xsl:template>

</xsl:stylesheet>