2015-09-06 71 views
0

我試圖使用ElementTree從.config文件中獲取數據。這個文件的結構是這樣的,例如:使用ElementTree解析.config文件中的數據時出錯

<userSettings> 
     <AutotaskUpdateTicketEstimatedHours.My.MySettings> 
      <setting name="Username" serializeAs="String"> 
       <value>AAA</value> 
      </setting> 

我的代碼是這樣的:

import os, sys 
import xml.etree.ElementTree as ET 


class Init(): 
    script_dir = os.path.dirname(__file__) 
    rel_path = "app.config" 
    abs_file_path = os.path.join(script_dir, rel_path) 

    tree = ET.parse(abs_file_path) 
    root = tree.getroot() 
    sites = root.iter('userSettings') 
    for site in sites: 
     apps = site.findall('AutotaskUpdateTicketEstimatedHours.My.MySettings') 
     for app in apps: 
      print(''.join([site.get('Username'), app.get('value')])) 


if __name__ == '__main__': 
    handler = Init() 

然而,當我運行此代碼,我得到:

Traceback (most recent call last): 
    File "/Users/AAAA/Documents/Aptana/AutotaskUpdateTicketEstimatedHours/Main.py", line 5, in <module> 
    class Init(): 
    File "/Users/AAA/Documents/Aptana/AutotaskUpdateTicketEstimatedHours/Main.py", line 16, in Init 
    print(''.join([site.get('Username'), app.get('value')])) 
TypeError: sequence item 0: expected string, NoneType found 

我」我做錯了原因這個錯誤?

(我的問題似乎訪問我config.file的樹結構正確)

+0

@perror我真的不明白你爲什麼會認爲這是重複的.. – feners

+0

我同意,我誤解了你的問題。看起來'用戶名'可能是'NoneType',那就是問題所在。抱歉。 – perror

+0

@perror是啊,但我相信它是因爲我沒有正確訪問樹結構,有任何幫助嗎? – feners

回答

2

您可以更改您的代碼:

print(''.join([app.get('name'), app.find('value').text])) 

app在這種情況下<setting>Element Object。使用get函數,您將通過名稱(例如name,serializeAs)獲得屬性值,使用find 函數,您將獲得一個子元素(例如<value>)。

一旦你有<value>你可以得到裏面的數據與text

注意site<AutotaskUpdateTicketEstimatedHours.My.MySettings>)沒有任何屬性,所以你得到None

+0

感謝您的幫助! – feners