2011-08-17 66 views
2

我正嘗試使用xslt將XML轉換爲csv,因此我不熟悉xslt,因此只是閱讀了一些教程和其他在線資源。 這裏是我的XML使用XSLT進行XML到CSV轉換

<?xml version="1.0" encoding="UTF-8"?> 
<impex> 
    <test> 
     <Employee /> 
     <UID>auma</UID> 
     <Name>HR Manager</Name> 
     <Groups /> 
     <Password>228781</Password> 
    </test> 
    <test> 
     <Employee /> 
     <UID>auma1</UID> 
     <Name>HR Manager</Name> 
     <Groups /> 
     <Password>2287811</Password> 
    </test> 
</impex> 

我使用的XML轉換以下XSL到csv

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:xs="http://www.w3.org/2001/XMLSchema" 
    xmlns:f="Functions" 
    version="2.0"> 

<xsl:output method="text" /> 
<xsl:param name="headerVal" select="'INSERT_UPDATE Employee;UID[unique=true];name;groups(uid);password'"/> 


<xsl:template match="/impex"> 
    <xsl:apply-templates select="test[1]/*" mode="header"/> 
    <xsl:apply-templates select="test" /> 
</xsl:template> 


<xsl:template match="*" mode="header" > 

    <xsl:value-of select="$headerVal" /> 
</xsl:template> 

<xsl:template match="test"> 
    <xsl:apply-templates select="*"/> 
</xsl:template> 

<xsl:template match="*" > 
    <xsl:value-of select="."/> 
    <xsl:choose> 
     <xsl:when test="position()=last()"> 
      <xsl:text>&#10;</xsl:text> 
     </xsl:when> 
     <xsl:otherwise>;</xsl:otherwise> 
    </xsl:choose> 
</xsl:template> 


</xsl:stylesheet> 

我試圖使用來定義我的CSV頭,但這個工作不適合我

CSV輸出

INSERT_UPDATEEmployeeUID[unique=true]namegroups(uid)password 
INSERT_UPDATEEmployeeUID[unique=true]namegroups(uid)password 
INSERT_UPDATEEmployeeUID[unique=true]namegroups(uid)password 
INSERT_UPDATEEmployeeUID[unique=true]namegroups(uid)password 
INSERT_UPDATEEmployeeUID[unique=true]namegroups(uid)password 
;auma;HR Manager;;228781 
;auma1;HR Manager;;2287811 

如下線

<xsl:param name="headerVal" select="'INSERT_UPDATE Employee;UID[unique=true];name;groups(uid);password'"/> 

我是假設它在select;是因爲,但我即使去掉它,甚至刪除的空間,但沒有任何幫助 我用Google搜索關於這一點,但無法找到一種方式,如何定義這個報頭我的XSL文件裏,這樣我可以提前用這個頭我的CSV

感謝

回答

1

問題解決。

<xsl:apply-templates select="test[1]/*" mode="header"/> 

這裏我選擇內部test[1],在我的XML的所有元素我有test元素內五行,所以我只是改變了這一行:

<xsl:apply-templates select="test[1]" mode="header"/> 

,它做工精細。

+0

謝謝SOOO發佈這個。這是我的問題的答案 - 做一些非常相似的事情。本質上,我也需要將XML轉換爲CSV。我的輸出比傳統格式更符合你的要求(頂部沒有INSERT語句)。 無論如何,mode =「header」技巧就是我所缺少的。 再一次,非常感謝你。 – tggagne