2017-08-16 74 views
0

我想將XML文件轉換爲使用Elementree的字典。 XML文件中有各種標籤,但對於每個記錄,ID標籤都是主鍵。所以我試圖創建的字典將父標記作爲ID,將所有其他屬性作爲其子鍵。但我得到一個unboundlocalerror,說'局部變量x是賦值前的引用。下面是代碼:Python:分配前的局部變量引用

tree = ET.parse(xml_file) 
root = tree.getroot() 
temp_dict={} 
def create_dict(): 
    test_dict = {} 
    for child in root.iter(): 
     if subchild.tag=='ID': 
       x=(child.text) 
     else: 
      test_dict[subchild.tag]= subchild.text 
     temp_dict[x]=test_dict 
    return (temp_dict) 
+0

我想我是能夠找出這一個。你能幫我解決這個問題嗎? https://stackoverflow.com/questions/45724345/python-unable-to-extract-attribute-using-xmltodict –

回答

0

這樣可不行,你必須初始化x值或condition和等待,直到第subchild被發現。
您還分配了x = test_dict而沒有()

例如使用條件,例如:

... 
temp_dict={} 
x = None 
def create_dict(): 
    ... 
     if subchild.tag=='ID': 
      x = test_dict 
    ... 
     if x: 
      temp_dict[x]=test_dict 

... 
+0

是的..我明白了!謝謝@stovfl –

相關問題