2016-10-14 17 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'}'並應用了'items )'循環,現在它工作。 –

相關問題