2013-04-07 2 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과 같이 말한다 : [errno를 2] 해당 파일이나 디렉토리 : 'C : \\ DATA \\ US_Patent_Data \ x812 \\ ipgb20120103_wk01 \\ ipgb20120103. xml'' etree.parse를 사용할 때마다 나는 항상 그런 것을 얻는다. –

+0

2012가 x812로 어떻게 바뀔 수 있는지는 이상하게도 이상하다. 나는 그것이 경로를 바꾸 었다고 생각한다. 나는 파일을 바탕 화면으로 옮겼다. 이제는 다른 오류를 준다. '파일 : C : \ Python27 \ lib \ site-packages \ elementtree \ ElementTree.py ", 1292 행의 파일 self._parser.Parse (data, 0) ExpatError : 문서 요소 다음의 junk : 414 행, 0 열 –

+0

Btw, 상대 경로를 사용할 수 있습니다. 예를 들어 xml 파일과 스크립트가 같은 디렉토리에 있으면 ET.parse ("ipgb20120103.xml"). 전체 오류 스택 추적을 제공하고 ur xml이 유효한지 확인하십시오. – alecxe

관련 문제