解析xml文件并将数据存储在数据库中

时间:2016-06-30 07:24:17

标签: xml python-2.7 xml-parsing

import MySQLdb
from xml.dom import minidom
import xml.dom.minidom

xmldoc = xml.dom.minidom.parse("Country.xml")

country= xmldoc.getElementsByTagName("country")[0]

sensors = country.getElementsByTagName("sensor")

for sensor in sensors:
    Translation = sensor.getElementsByTagName("Translation")[0].firstChild.data
    Name = sensor.getElementsByTagName("Name")[0].firstChild.data
    Prefix = sensor.getElementsByTagName("Prefix")[0].firstChild.data
    Percentage = sensor.getElementsByTagName("Percentage")[0].firstChild.data
    Position = sensor.getElementsByTagName("Position")[0].firstChild.data

    db = MySQLdb.connect("localhost","root","akshay","country")

# prepare a cursor object using cursor() method
cursor = db.cursor()

# Drop table if it already exist using execute() method.
cursor.execute("DROP TABLE IF EXISTS country_table")

# Create table as per requirement
sql = """CREATE TABLE country_table (_
         Translation  VARCHAR(20) NOT NULL,
         Name  VARCHAR(20) NOT NULL,
         Prefix INT(5) NOT NULL,  
         Percentage INT(3) NOT NULL,
         Position INT(3) NOT NULL
          )"""

sql1= ("INSERT INTO country_table(Translation, Name, Prefix, Percentage,Position) VALUES(%s, %s, %s, %s,%s)"
   %(Translation, Name, Prefix, Percentage,Position))

try:
   # Execute the SQL command

     cursor.execute(sql1)

except:
   # Rollback in case there is any error
   db.rollback()

# disconnect from server
db.close()

我收到以下错误:

  

Traceback(最近一次调用最后一次):文件“test.py”,第5行,in          xmldoc = xml.dom.minidom.parse(“Country.xml”)File“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/dom/minidom.py”,   1918年,在解析       return expatbuilder.parse(file)File“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/dom/expatbuilder.py”,   第924行,解析       result = builder.parseFile(fp)File“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/dom/expatbuilder.py”,   第211行,在parseFile中       parser.Parse(“”,True)xml.parsers.expat.ExpatError:找不到元素:第43行,第0列

请帮忙。

1 个答案:

答案 0 :(得分:0)

您尚未关闭始发和交易代码,只需关闭它们即可正常使用。