2

私はxsltが初めてです。入力をxmlとして取得するxsltを使用してjsonを生成する必要があります。

ここで私の入力xmlは次のようになります

<root> 
<section>   
  <item name="a">  
       <uuid>1</uuid>  
          </item> 
   </section> 
 <section>    
 <item name="b">     
     <uuid>2</uuid>  
   </item> 
     </section> 
   </root> 

xslt を使用して、このような出力を取得する必要があります

{ "root" : { "section" : { "item" :[{ "name" : "a", "uuid" : "1"},
                                    { "name" : "b", "uuid" : "2"}] }
}}

ここで私がしなければならないことは次のとおりです。

  1. 子ノードが配列内で同じ名前を持っているかどうかを調べる

  2. それらが同じ名前を持つ場合、同じノード名の下にそのノード値を含む配列を生成します

出力は json である必要があります。

4

1 に答える 1

0

一般に、XML ドキュメントと JSON オブジェクトの間には 1:1 のマッピングはありません。これは、2 つの言語とその表現力の違いによるものです。

これは、あなたの特定のケースでは、この変換

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

 <xsl:variable name="vQ">"</xsl:variable>

 <xsl:template match="/*">
{ "root" : { "section" :
 <xsl:apply-templates select="section[1]/*"/>
 }}
 </xsl:template>

 <xsl:template match="item">
  { "item" :
    [<xsl:text/>
      <xsl:apply-templates select="../../*/item" mode="data"/>
     ]
   }
 </xsl:template>

 <xsl:template match="item" mode="data">
   <xsl:if test="position() > 1">, &#xA;&#9;&#9; </xsl:if>
   <xsl:text>{</xsl:text><xsl:apply-templates select="@*|*"/>}<xsl:text/>
 </xsl:template>

 <xsl:template match="item/@* | item/*">
   <xsl:if test="position() > 1">, </xsl:if>
   <xsl:value-of select='concat($vQ, name(), $vQ, " : ", $vQ, ., $vQ)'/>
 </xsl:template>
</xsl:stylesheet>

提供された XML ドキュメントに適用した場合:

<root>
    <section>
        <item name="a">
            <uuid>1</uuid>
        </item>
    </section>
    <section>
        <item name="b">
            <uuid>2</uuid>
        </item>
    </section>
</root>

必要な結果を生成します:

{ "root" : { "section" :

  { "item" :
    [{"name" : "a", "uuid" : "1"}, 
         {"name" : "b", "uuid" : "2"}
     ]
   }

 }}
于 2012-06-22T12:33:14.203 に答える