tags:

views:

48

answers:

1

Hi,

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 simply 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.

+1  A: 

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 file
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))
cur.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)
Daniel Hepper
Meaning that I open the XML/HTML file and copy the contents into the text column? Not being able to query the values is alright for my scenario. I'm sorry if I sound rather stupid, its my first time dealing with databases and XML together.
M Rubern C