2016-10-14 6 views
0

私はPython 3.5を実行しています。XML SubElementsを作成し、別の要素の下に追加する関数を定義しました。属性は辞書にありますが、何らかの理由でスクリプトを実行するときに辞書のキーと値が反転することがあります。 (私はここでそれを組み合わせたように、多くの機能にコードが壊れている)。ここ 予期せず辞書のキーと値が反転する

import xml.etree.ElementTree as ElementTree 

def AddSubElement(parent, tag, text='', attributes = None): 
    XMLelement = ElementTree.SubElement(parent, tag) 
    XMLelement.text = text 
    if attributes != None: 
     for key, value in attributes: 
      XMLelement.set(key, value) 
    print("attributes =",attributes) 
    return XMLelement 

descriptionTags = ([('xmlns:g' , 'http://base.google.com/ns/1.0')]) 
XMLroot = ElementTree.Element('rss') 
XMLroot.set('version', '2.0') 
XMLchannel = ElementTree.SubElement(XMLroot,'channel') 
AddSubElement(XMLchannel,'g:description', 'sporting goods', attributes=descriptionTags) 
AddSubElement(XMLchannel,'link', 'http://'+ domain +'/') 
XMLitem = AddSubElement(XMLchannel,'item') 
AddSubElement(XMLitem, 'g:brand', Product['ProductManufacturer'], attributes=bindingParam) 
AddSubElement(XMLitem, 'g:description', Product['ProductDescriptionShort'], attributes=bindingParam) 
AddSubElement(XMLitem, 'g:price', Product['ProductPrice'] + ' USD', attributes=bindingParam) 

キーと値を切り替える取得ん私が持っているものの種類の抜粋です!

attributes = [{'xmlns:g', 'http://base.google.com/ns/1.0'}] 
attributes = [{'http://base.google.com/ns/1.0', 'xmlns:g'}] 
attributes = [{'http://base.google.com/ns/1.0', 'xmlns:g'}] 
... 

そして、ここでは時々出てくることをXML文字列です::

<rss version="2.0"> 
<channel> 
    <title>example.com</title> 
    <g:description xmlns:g="http://base.google.com/ns/1.0">sporting goods</g:description> 
    <link>http://www.example.com/</link> 
    <item> 
     <g:id http://base.google.com/ns/1.0="xmlns:g">8987983</g:id> 
     <title>Some cool product</title> 
     <g:brand http://base.google.com/ns/1.0="xmlns:g">Cool</g:brand> 
     <g:description http://base.google.com/ns/1.0="xmlns:g">Why is this so cool?</g:description> 
     <g:price http://base.google.com/ns/1.0="xmlns:g">69.00 USD</g:price> 
     ... 

これが反転する原因となっている私は時々コンソールでこれを表示されますので、?

+0

これは辞書ではありません... –

答えて

3
attributes = [{'xmlns:g', 'http://base.google.com/ns/1.0'}] 

これは辞書ではなく、セットを含むリストです。セットも辞書も注文されません。

+0

ありがとうございます、私は 'descriptionTags'を' {'xmlns:g': 'http://base.google.com/ns/1.0'} 'に変更し、 ) 'をループに追加し、今は動作します。 –

関連する問題