2013-08-19 159 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 –