2013-04-07 61 views
1

這段代碼我得到了互聯網上的某個地方,我編輯它。如何從目錄加載XML文件請

如何從我的目錄加載XML文件?有沒有辦法做到這一點?

from elementtree import ElementTree as et 
# Load the xml content from a string 
content = et.fromstring("C:\DATA\US_Patent_Data\2012\ipgb20120103_wk01\ipgb20120103.xml") 


# Get the person or use the .findall method to get all 
# people if there's more than person 
applicant = content.find("applicant") 
last_name = applicant.find("addressbook/last-name") 
first_name = applicant.find("addressbook/first-name") 

# Get the persons address 
address = addressbook.find("address") 
street = address.find("street") 
city= address.find("city") 
state = address.find("state") 
postcode = address.find("postcode") 
country = address.find("country") 

# Print output 
print "sequence: " + applicant.attrib.get('sequence') 
print "first name: " + first_name.text 
print "last name: " + last_name.text 
print "street: " + street.text 
print "city: " + city.text 
print "state: " + state.text 
print "postcode: " + postcode.text 
print "country: " + country.text 

我跑這個程序,這就是我得到的。 我複製他們的一部分...

File "C:\Python27\lib\site-packages\elementtree\ElementTree.py", line 1292, in feed 
self._parser.Parse(data, 0) 

ExpatError:沒有很好地形成(標記無效):第1行,第2列

回答

1

fromstring功能是用於從字符串讀取XML數據。

對於從文件中讀取xml數據,您應該使用parse。有關使用elementtree解析xml的信息,請參閱docs

import xml.etree.ElementTree as ET 
tree = ET.parse("C:\DATA\US_Patent_Data\2012\ipgb20120103_wk01\ipgb20120103.xml") 
root = tree.getroot() 

UPD: 好像沒有很好地形成你的XML,因爲它有多個根。嘗試添加一個根元素:

with open('ipgb20120103.xml', 'r') as f: 
    xml_string = "<root>%s</root>" % f.read() 

root = ET.fromstring(xml_string) 
+0

它說像this.'IOError:[錯誤2]沒有這樣的文件或目錄:「C:\\ DATA \\ US_Patent_Data \ x812 \\ ipgb20120103_wk01 \\ ipgb20120103。 xml''每當我使用etree.parse,我總是會得到類似的東西 – 2013-04-07 09:10:50

+0

2012年可以更改爲x812是很奇怪的。我認爲它改變了路徑...我已經將文件移動到桌面,現在它給我提供了不同的錯誤 '文件「C:\ Python27 \ lib \ site-packages \ elementtree \ ElementTree.py」,行1292, self._parser.Parse(data,0) ExpatError:文檔元素之後的垃圾:行414,列0' – 2013-04-07 09:20:28

+0

順便說一句,你可以使用相對路徑。例如,如果xml文件和腳本位於相同目錄中:ET.parse(「ipgb20120103.xml」)。請提供完整的錯誤堆棧跟蹤,並確保您的xml是有效的。 – alecxe 2013-04-07 10:02:07