这段代码我在互联网上的某个地方编辑了它。
如何从我的目录加载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列
答案 0 :(得分:2)
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)