开发者

Storing XML/HTML files inside a SQLite database - Possible?

开发者 https://www.devze.com 2023-01-05 18:28 出处:网络
Is it possible to directly store a XML/HTML file inside a SQLite database? I\'m writing a program in python which is supposed to parse XML/HTML files and store the values inside the database. However

Is it possible to directly store a XML/HTML file inside a SQLite database?

I'm writing a program in python which is supposed to parse XML/HTML files and store the values inside the database. However, the fields inside the XML/HTML files may vary and I thought it would be easier to s开发者_如何学Goimply store the entire XML/HTML file inside the database and then parse it only when used.

Is this possible with python and SQLite? Or am I approaching this problem from the wrong angle?

Thanks in advance!

EDIT: Could anyone share a code sample on how one would store the file? I understand that it is possible but I'm unsure on how to go about doing it.


You can store your XML/HTML file as text without problems in a text column.

The obvious downside is that you can't really query for the values in your XML.

Edit: Here is an example. Just read your XML file into a variable and store it in the DB like you would store any string, alongside with any other values you want to store. When you want to use the XML, just read it from DB and parse it with an XML parser.

# connect to database and create table
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute('''create table my_table (value1 integer, value2 integer, xml text)''')

# read text from your input file containing xml
f = file('/tmp/my_file.xml')
xml_string_from_file = f.read()

# insert text into database
cur = conn.cursor()
cur.execute('''insert into my_table (value1, value2, xml) values (?, ?, ?)''', (23, 42, xml_string_from_file))
conn.commit()

# read from database into variable
cur.execute('''select * from my_table''')
xml_string_from_db = cur.fetchone()[2]

# parse with the XML parser of your choice
from xml.dom.minidom import parseString
dom = parseString(xml_string_from_db)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号