2010-01-18 24 views
7

Tengo una pregunta relacionada con algunas guías para resolver un problema. Tengo conmigo un archivo xml, tengo que poblarlo en un sistema de base de datos (lo que sea, podría ser sqlite, mysql) usando el lenguaje de scripting: Python.poblando datos del archivo xml a una base de datos sqlite usando python

¿Alguien tiene alguna idea de cómo proceder?

  • ¿Qué tecnologías necesito leer más?
  • ¿Qué entornos tengo que instalar?
  • ¿Tienes algún tutorial sobre el mismo tema?

Ya traté de analizar el xml utilizando métodos arborescentes y de saxo en otro idioma, pero para comenzar con Python, no sé por dónde empezar. Ya sé cómo diseñar la base de datos que necesito.

Otra pregunta, ¿es posible Python solo para ejecutar consultas de ddl de base de datos?

Respuesta

8

Le recomiendo estudiar en su archivo XML en la memoria (analizarlo todo, luego emitirlo a un SQL DB, es probablemente más fácil, pero el árbol de elementos también permite el funcionamiento incremental si el archivo es enorme) - - Es parte de la biblioteca estándar de Python como módulo xml.etree.

recomiendo sqlite3 (también en la biblioteca estándar de Python) como la base de datos relacional de elección (si usted tiene una opción), de nuevo porque es práctico y fácil - los SQLite subyacentes incrustados relacional DB también está bien documentada en its own site. Si necesita un tutorial general sobre cómo Python le gusta interactuar con los DB relacionales (el "DB-API"), hay uno agradable, here.

Una vez que comprenda completamente etree y sqlite3 - y no necesariamente necesita instalar cualquier cosa para cualquiera (que es parte de sus encantos ;-) - básicamente está todo listo. (Por supuesto, una instalación de SQLite en sí misma (línea de comandos y/o herramientas GUI) para que pueda ver sus archivos DB y modificarlos puede ser bueno, como pueden los editores XML gráficos como oXygen o XMLmind para ver y/o modificar su XML , pero ningún tipo de herramienta es en absoluto necesario, para nada relacionado con el uso de Python en lugar de otros lenguajes para el análisis XML y la escritura SQLite ;-).

Y sí, puede perfectamente hacer CREATE TABLE y otras consultas DDL de sqlite3 (y cualquier otro módulo de Python compatible con DB-API, si usted elige utilizar otras DB relacionales ;-).

+1

+1 por dirigirme a elementtree. PD. ¿Fue "DLL consulta" un error tipográfico y se supone que es "consultas DDL" como en el lenguaje de definición de datos? – Davos

+0

@Davos, sí, fue un error tipográfico para DDL, arreglando ahora, gracias. –

1

Si está acostumbrado a DOM (árbol) el acceso a XML desde otro lenguaje, que puede encontrar útiles estos módulos estándar de la biblioteca (y sus respectivos documentos):

  • xml.dom
  • xml.dom .minidom

Para guardar los datos en DB, puede usar el módulo estándar sqlite3 o buscar el enlace a mysql. O puede usar algo más abstracto, como SQLAlchemy o el ORM de Django.

6

Puede hacerlo todo a mano con sqlite3 y xmlstarlet.

  • convertir XML a CSV
  • csv importación a db.

(Tal vez no es su deseo. Pero es muy útil)

# content of xml file 
$ cat artist.xml 
<results><artist><id>Ae2300d8b0232c06c</id><name>莎拉 布莱曼(Sarah Brightman)</name><hotSongs><!--freemusic/song/result/Sa3f6b810d7f98646--><song><id>Sa3f6b810d7f98646</id><name>Gloomy Sunday</name><artist>莎拉 布莱曼(Sarah Brightman)</artist><artistId>Ae2300d8b0232c06c</artistId><album>月光女神</album><duration>227.0</duration><canBeDownloaded>true</canBeDownloaded><hasFullLyrics>true</hasFullLyrics><canBeStreamed>true</canBeStreamed><albumId>Bfef909d41922984a</albumId><hasSimilarSongs>true</hasSimilarSongs><hasRecommendation>false</hasRecommendation></song><!--freemusic/song/result/Sbb94fa21258a8b51--><song><id>Sbb94fa21258a8b51</id><name>我和你(2008年奥运会主题曲)(You And Me)</name><artist>刘欢</artist><artist>莎拉 布莱曼(Sarah Brightman)</artist><artistId>A6682d46bd4bdfc84</artistId><artistId>Ae2300d8b0232c06c</artistId><album>我和你 2008北京奥运会主题歌</album><duration>256.0</duration><canBeDownloaded>true</canBeDownloaded><hasFullLyrics>true</hasFullLyrics><canBeStreamed>true</canBeStreamed><albumId>Babf3ab3b7ef0e3ed</albumId><hasSimilarSongs>true</hasSimilarSongs><hasRecommendation>false</hasRecommendation></song><!--freemusic/song/result/S6a47788bef57ff87--><song><id>S6a47788bef57ff87</id><name>Scarborough Fair</name><artist>莎拉 布莱曼(Sarah Brightman)</artist><artistId>Ae2300d8b0232c06c</artistId><album>月光女神</album><duration>251.0</duration><canBeDownloaded>true</canBeDownloaded><hasFullLyrics>true</hasFullLyrics><canBeStreamed>true</canBeStreamed><albumId>Bfef909d41922984a</albumId><hasSimilarSongs>true</hasSimilarSongs><hasRecommendation>false</hasRecommendation></song><!--freemusic/song/result/Sde1aa68da126ddfe--><song><id>Sde1aa68da126ddfe</id><name>Time To Say Goodbye</name><artist>莎拉 布莱曼(Sarah Brightman)</artist><artistId>Ae2300d8b0232c06c</artistId><album>Symphony: Live In Vienna</album><duration>275.0</duration><canBeDownloaded>true</canBeDownloaded><hasFullLyrics>true</hasFullLyrics><canBeStreamed>true</canBeStreamed><albumId>B0187937a07b940f7</albumId><hasSimilarSongs>true</hasSimilarSongs><hasRecommendation>false</hasRecommendation></song><!--freemusic/song/result/S7483cc8c44e06bbb--><song><id>S7483cc8c44e06bbb</id><name>Amazing Grace</name><artist>莎拉 布莱曼(Sarah Brightman)</artist><artistId>Ae2300d8b0232c06c</artistId><album>真爱永恒 - 冬之歌</album><duration>186.0</duration><canBeDownloaded>true</canBeDownloaded><hasFullLyrics>true</hasFullLyrics><canBeStreamed>true</canBeStreamed><albumId>B38e85a3056c0381c</albumId><hasSimilarSongs>true</hasSimilarSongs><hasRecommendation>false</hasRecommendation></song><!--freemusic/song/result/S2d9683c7230e18de--><song><id>S2d9683c7230e18de</id><name>This Love</name><artist>莎拉 布莱曼(Sarah Brightman)</artist><artistId>Ae2300d8b0232c06c</artistId><album>月光女神</album><duration>371.0</duration><canBeDownloaded>true</canBeDownloaded><hasFullLyrics>true</hasFullLyrics><canBeStreamed>true</canBeStreamed><albumId>Bfef909d41922984a</albumId><hasSimilarSongs>true</hasSimilarSongs><hasRecommendation>false</hasRecommendation></song><!--freemusic/song/result/Scfb4989195b44e57--><song><id>Scfb4989195b44e57</id><name>Here With Me</name><artist>莎拉 布莱曼(Sarah Brightman)</artist><artistId>Ae2300d8b0232c06c</artistId><album>月光女神</album><duration>324.0</duration><canBeDownloaded>true</canBeDownloaded><hasFullLyrics>true</hasFullLyrics><canBeStreamed>true</canBeStreamed><albumId>Bfef909d41922984a</albumId><hasSimilarSongs>true</hasSimilarSongs><hasRecommendation>false</hasRecommendation></song><!--freemusic/song/result/S7bafc588178b932c--><song><id>S7bafc588178b932c</id><name>La Lune</name><artist>莎拉 布莱曼(Sarah Brightman)</artist><artistId>Ae2300d8b0232c06c</artistId><album>月光女神</album><duration>173.0</duration><canBeDownloaded>true</canBeDownloaded><hasFullLyrics>false</hasFullLyrics><canBeStreamed>true</canBeStreamed><albumId>Bfef909d41922984a</albumId><hasSimilarSongs>true</hasSimilarSongs><hasRecommendation>false</hasRecommendation></song></hotSongs></artist></results> 

# convert xml to csv file using xmlstarlet 
$ xml sel -t -m '//song' -v 'concat(id, ",", name, ",", duration)' -n artist.xml | sed '$d' >artist.csv 

# content of csv file 
$ cat artist.csv 
Sa3f6b810d7f98646,Gloomy Sunday,227.0 
Sbb94fa21258a8b51,我和你(2008年奥运会主题曲)(You And Me),256.0 
S6a47788bef57ff87,Scarborough Fair,251.0 
Sde1aa68da126ddfe,Time To Say Goodbye,275.0 
S7483cc8c44e06bbb,Amazing Grace,186.0 
S2d9683c7230e18de,This Love,371.0 
Scfb4989195b44e57,Here With Me,324.0 
S7bafc588178b932c,La Lune,173.0 

# create sqlite database 
$ sqlite3 song.db 
sqlite> CREATE TABLE song(id, name, duration); 

# enter csv mode to import csv file 
sqlite> .mode csv 
sqlite> .import artist.csv song 

# check everything is ok 
sqlite> .mode column 
sqlite> .header on 
sqlite> select * from song; 
id     name   duration 
----------------- ------------- ---------- 
Sa3f6b810d7f98646 Gloomy Sunday 227.0 
Sbb94fa21258a8b51 我和你(200 256.0 
S6a47788bef57ff87 Scarborough F 251.0 
Sde1aa68da126ddfe Time To Say G 275.0 
S7483cc8c44e06bbb Amazing Grace 186.0 
S2d9683c7230e18de This Love  371.0 
Scfb4989195b44e57 Here With Me 324.0 
S7bafc588178b932c La Lune  173.0 
Cuestiones relacionadas