2015-01-16 39 views
0

我正在使用spyne Array來轉換JSON列表,並且需要將「id」屬性添加到最終XML中的「referral」父節點。如何將屬性添加到Spyne Array中的所有XMLElements中

這是最後的XML我期待:

<viewOutboundResponse user="rayners"> 
    <referral id="123"> 
     <status>SUBMITTED</status> 
     <from> 
      <outlet id="12345">ABC</outlet> 
     </from> 
     <to> 
      <outlet id="6789">XYZ</outlet> 
     </to> 
     <date>2015-01-14</date> 
     <client>Bloggs</client> 
     <daysToExpiry>3</daysToExpiry> 
    </referral> 
    <referral id="456"> 
     <status>REJECTED</status> 
     <from> 
      <outlet id="101112">DEF</outlet> 
     </from> 
     <to> 
      <outlet id="131415">S2X Demo</outlet> 
     </to> 
     <date>2004-01-15</date> 
     <client>Gobbs</client> 
     <daysToExpiry>7</daysToExpiry> 
    </referral> 
</viewOutboundResponse> 

這裏是我的代碼:

class ReferralSummaryType(ComplexModel): 
    __type_name__ = 'referral' 
    type_info = {'id': XmlAttribute(Integer), 
       'status': Unicode, 
       'from': ReferralFromType, 
       'to': ReferralToType, 
       'date': Date, 
       'client': Unicode, 
       'daysToExpiry': Integer} 


class OutboundResponseType(ComplexModel): 
    __mixin__ = True 
    referral = Array(ReferralSummaryType) 

但我得到的輸出:

<viewOutboundResponse user="rayners"> 
    <referral> 
     <referral id="123"> 
      <status>SUBMITTED</status> 
      <from> 
       <outlet id="12345">ABC</outlet> 
      </from> 
      <to> 
       <outlet id="6789">XYZ</outlet> 
      </to> 
      <date>2015-01-14</date> 
      <client>Bloggs</client> 
      <daysToExpiry>3</daysToExpiry> 
     </referral> 
     <referral id="456"> 
      <status>REJECTED</status> 
      <from> 
       <outlet id="101112">DEF</outlet> 
      </from> 
      <to> 
       <outlet id="131415">S2X Demo</outlet> 
      </to> 
      <date>2004-01-15</date> 
      <client>Gobbs</client> 
      <daysToExpiry>7</daysToExpiry> 
     </referral> 
    </referral> 
</viewOutboundResponse> 

回答

0

所以你的問題說

我需要將「id」屬性添加到 最終XML中的「referral」父節點。

所需輸出具有轉診節點的未經包裝轉​​診節點,並且看到的結果的序列是嵌入轉診節點的序列(每個具有id屬性),但包裝節點上沒有ID。

所以這裏有一點衝突。如果這是你需要有一個ID在包裝轉診節點,那麼我想你可能需要改變你的迴應,並添加類包裝類型:

class ReferralWrapperType(ComplexModel): 
    __type_name__ = 'referral' 
    id = XMLAttribute(Integer) 
    referral = Array(ReferralSummaryType) 


class OutboundResponseType(ComplexModel): 
    __mixin__ = True 
    referral = ReferralWrapperType 

而如果你需要的是什麼顯示在你說的是,你從Spyne array documentation導致我相信,你也許可以嘗試期待那麼最終的XML:

class OutboundResponseType(ComplexModel): 
    __mixin__ = True 
    referral = ReferralSummaryType.customize(max_occurs="unbounded") 

警告 - 我非常非常非常新的Spyne。 編輯爲使用max_occurs =「unbounded」而不是max_occurs = float('inf')每this spyne bug

相關問題