2011-09-01 50 views
2

我需要使用xslt將xml結構轉換爲文本字符串。我有一個XML結構是這樣的:如何將node = value對與&seprator連接起來

<index> 
    <account index="0">00000000000</account> 
    <customerId index="0">1112xxxxxxx</customerId> 
    <authorization>1</authorization> 
    <access>1</access> 
    <documentGroup>1</documentGroup> 
    <documentType>165200</documentType> 
    <!-- Any number of child nodes --> 
</index> 

我需要改變這個作爲後的參數是這樣的:

account=00000000000&customerId=1112xxxxxxx&authorization=1..... 

就如何實現這一目標的任何想法?

回答

3

需要注意的是,如果你不侷限於XSLT 1.0,您可以使用擴展XSLT 2.0 xsl:value-of和所有減少到一個模板:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="text"/> 

    <xsl:template match="index"> 
     <xsl:value-of select="*/concat(local-name(),'=',.)" separator="&amp;"/> 
    </xsl:template> 

</xsl:stylesheet> 

即使在XSLT 1.0,你可以將所有減少單模板,無需採用任何迭代指令:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="text"/> 
    <xsl:strip-space elements="*"/> 

    <xsl:template match="index/*"> 
     <xsl:if test="position()>1"> 
      <xsl:text>&amp;</xsl:text> 
     </xsl:if> 
     <xsl:value-of select="concat(local-name(), '=', .)"/> 
    </xsl:template> 

</xsl:stylesheet> 
+1

這是所有三種解決方案中的最佳解決方案,比接受的答案要好得多。 +1。 –

+0

謝謝@Dimitre,你讓我興奮起來。 –

+1

酷:-),我也是+1。 – actionshrimp

1

像這樣的東西應該做你需要的。您可能需要注意與&amp;實體編碼,雖然,但xsl:output method="text"應該照顧這:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format"> 
    <xsl:output method="text"/> 
    <xsl:template match="index"> 
     <xsl:variable name="len" select="count(*)"/> 
     <xsl:for-each select="*"> 
      <xsl:value-of select="name()"/>=<xsl:value-of select="."/><xsl:choose> 
       <xsl:when test="position() &lt; $len">&amp;</xsl:when> 
      </xsl:choose> 
     </xsl:for-each> 
    </xsl:template> 
</xsl:stylesheet> 

這不會「逃離」的字符串,雖然(即轉換之類的空間爲%20),其可能會導致你的問題,但是對於我認爲是你面臨的主要問題的任何數量的子節點都適用?

+0

太棒了!非常感謝,這很好用:)我做的唯一更改是使用local-name()而不是name()來刪除任何名稱空間前綴(如果存在)。 – eirik

+0

但@_erik:但請參閱並考慮接受@empo更好的解決方案。 –

0
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="text" indent="yes"/> 

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

    <xsl:template match="*"> 
     <xsl:value-of select="concat(local-name(), '=', .)"/> 
     <xsl:if test="following-sibling::*"> 
      <xsl:text>&amp;</xsl:text> 
     </xsl:if> 
    </xsl:template> 
</xsl:stylesheet> 
相關問題