3

这段代码是我在互联网上的某个地方得到的,我对其进行了编辑。

如何从我的目录加载 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 列

4

1 回答 1

2

fromstring函数用于从字符串中读取 xml 数据。

要从文件中读取 xml 数据,您应该使用parse. 请参阅有关使用 elementtree 解析 xml 的文档

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)
于 2013-04-07T08:49:01.623 回答