2013-08-19 158 views
2

我正在嘗試使用XSLT將一些簡單的XML轉換爲JSON。使用XSLT將此XML轉換爲JSON

我的XML如下所示:

<some_xml> 
<a> 
<b> 
    <c foo="bar1"> 
    <listing n="1">a</listing> 
    <listing n="2">b</listing> 
    <listing n="3">c</listing> 
    <listing n="4">d</listing> 
    </c> 
    <c foo="bar2"> 
    <listing n="1">e</listing> 
    <listing n="2">b</listing> 
    <listing n="3">n</listing> 
    <listing n="4">d</listing> 
    </c> 
</b> 
</a> 
</some_xml> 

輸出看起來應該像下面這樣:

{ 
    "my_c": [ 
     { 
      "c": { 
       "foo_id": "bar1", 
       "listing_1": "a", 
       "listing_2": "b", 
       "listing_3": "c", 
       "listing_4": "d" 

      } 
     }, 
     { 
      "c": { 
       "foo_id": "bar2", 
       "listing_1": "e", 
       "listing_2": "b", 
       "listing_3": "n", 
       "listing_4": "d" 
      } 
     } 
    ], 
} 

我的XSLT試圖讓這個翻譯工作:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="text" omit-xml-declaration="yes" /> 
    <xsl:template match="/some_xml"> 
    { 
     "my_c": [ 
      <xsl:for-each select="a/b/c"> 
      { 
       "c": { 
       "foo_id": <xsl:value-of select="@foo">, 
       "listing_1": <xsl:value-of select="current()/listing[@n='1']" />, 
       "listing_2": <xsl:value-of select="current()/listing[@n='2']" />, 
       "listing_3": <xsl:value-of select="current()/listing[@n='3']" />, 
       "listing_4": <xsl:value-of select="current()/listing[@n='4']" /> 
       } 
      }, 
      </xsl:for-each> 
     ], 
    } 
    </xsl:template> 
</xsl:stylesheet> 

而下面的輸出是什麼結果:

{ 
"my_c": [ 

      { 
       "c": { 
       "foo_id": "bar1" 
     ], 
     } 
    } 

      { 
       "c": { 
       "foo_id": "bar2" 
     ], 
     } 
} 

我的XSLT在哪裏出錯?

回答

2

請嘗試正確關閉您的第一個xsl:value-of

此:<xsl:value-of select="@foo">

應該是:<xsl:value-of select="@foo"/>

如果我改變它,我得到這個輸出(這是接近你想要的輸出,但你仍然有工作的一點點左):

{ 
    "my_c": [ 

     { 
     "c": { 
     "foo_id": bar1, 
      "listing_1": a, 
      "listing_2": b, 
      "listing_3": c, 
      "listing_4": d 
      } 
      }, 

     { 
     "c": { 
     "foo_id": bar2, 
      "listing_1": e, 
      "listing_2": b, 
      "listing_3": n, 
      "listing_4": d 
      } 
      }, 

    ], 
    } 

此外,你不應該需要current()

+0

令人驚歎。不知道這麼多的傷害可以做到。我希望在這種情況下會出現解析器錯誤。很好,丹尼爾。謝謝。 – randombits

+0

有沒有一種方法可以在最後擺脫額外的逗號。即在您發佈的輸出的第22行之後和第24行之後的逗號。由於這些額外的逗號,我得到了JSON eval錯誤。 – CCoder

+0

看起來像你的問題在這裏回答:http://stackoverflow.com/questions/20658307/problems-converting-xml-to-json-using-xslt –