• Publicidad

Pasar consulta SQL a XML predefinido

¿Ya sabes lo que es una referencia? Has progresado, el nível básico es cosa del pasado y ahora estás listo para el siguiente nivel.

Pasar consulta SQL a XML predefinido

Notapor dmon_30 » 2012-09-10 04:30 @229

Buenas, saludos a todos.

Pues básicamente es eso, necesito pasar el resultado de una consulta SQL a un formato XML ya predefinido y escribirlo en un archivo.

La consulta a la base de datos ya la tengo resuelta, pero toda la información que me reporta no sé cómo tratarla y colocarla en el xml con formato ya predefinido.

Intenté utilizar XML::Simple y XML::Schema, pero no lo consigo.

Muchas gracias y saludos a todos...

Sintáxis: (query2.pl) [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/perl -w
  2.  
  3. use strict;
  4. use DBI;
  5.  
  6. my $dsn = 'DBI:ODBC:Driver={SQL Server}';
  7. my $host = '192.168.1.69,1433';
  8. my $database = 'Discografia';
  9. my $user = 'sa';
  10. my $auth = '';
  11.  
  12. #my $fech = strftime;
  13. # Connectamos via DBD::ODBC by specifying the DSN dynamically.
  14. my $dbh = DBI->connect("$dsn;Server=$host;Database=$database",
  15.                                                         $user,
  16.                                                         $auth,
  17.                                                         { RaiseError => 1, AutoCommit => 1}
  18.                                                         ) || die "Database connection not made: $DBI::errstr";
  19. #Preparamos la consulta SQL
  20. # es una prueba ... my $sql = "SELECT Canal, Config_Canales.Descripcion as Cd from aire,Config_Canales where aire.Canal=Config_Canales.Id and fecha ='2009-01-01' GROUP by Canal, Config_Canales.Descripcion";
  21. my $sql = "SELECT Canal, Config_Canales.Descripcion AS Cd, Fecha, Categoria, Hora_salida AS Hs, horainicio, Temas.Duracion AS Td, interprete, Temas.Titulo, codigo_cd AS Ccd FROM aire,Config_Canales,Temas where aire.Canal=Config_Canales.Id and aire.Codigo_cd=Temas.idDiscoCorte and fecha ='2009-01-01' order by Canal, Cd, horainicio ASC";
  22. my $sth = $dbh->prepare( $sql );
  23. #Execute the statement
  24. $sth->execute();
  25. # es una prueba ... my( $Canal, $Cd );
  26. my( $Canal, $Cd, $Fecha, $Categoria, $Hs, $horainicio, $Td, $interprete, $titulo, $Ccd );
  27. # Bind the results to the local variables
  28. #es una prueba . . .$sth->bind_columns( undef, \$Canal, \$Cd );
  29. $sth->bind_columns( undef, \$Canal, \$Cd, \$Fecha, \$Categoria, \$Hs, \$horainicio, \$Td, \$interprete, \$titulo, \$Ccd );
  30. #Retrieve values from the result set
  31. while( $sth->fetch() ) {
  32. print "$Canal, $Cd, $Fecha, $Categoria, $Hs, $horainicio, $Td, $interprete, $titulo, $Ccd\n";
  33. };
  34. $sth->finish();
  35. $dbh->disconnect();
Coloreado en 0.003 segundos, usando GeSHi 1.0.8.4

Resultado de la consulta:
Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
  1. 23,  023 - (RMS) MEDITERRANEO 2009-01-01 00:00:00.000, 5201, 1899-12-30 05:29:30.000, 1899-12-30 05:26:51.000, 239, MAXWELL, THE URBAN THEME, 01432801
  2. 23,  023 - (RMS) MEDITERRANEO 2009-01-01 00:00:00.000, 5201, 1899-12-30 05:34:24.000, 1899-12-30 05:29:30.000, 448, LOUNGE CAFE, FORMENTERA AMBIANCE, 01526001
  3. 23,  023 - (RMS) MEDITERRANEO 2009-01-01 00:00:00.000, 5201, 1899-12-30 05:40:15.000, 1899-12-30 05:34:18.000, 551, GOLOKA, GIVE ME LOVING, 01541507
  4. 23,  023 - (RMS) MEDITERRANEO 2009-01-01 00:00:00.000, 5201, 1899-12-30 05:44:55.000, 1899-12-30 05:40:09.000, 445, JONATHAN BADICHI, BLACK MUSIC, 01289910
  5. 23,  023 - (RMS) MEDITERRANEO 2009-01-01 00:00:00.000, 5201, 1899-12-30 05:48:55.000, 1899-12-30 05:44:54.000, 357, BLANK & JONES, MIND OF THE WONDERFUL, 01469203
  6. 23,  023 - (RMS) MEDITERRANEO 2009-01-01 00:00:00.000, 5201, 1899-12-30 05:51:28.000, 1899-12-30 05:48:51.000, 237, DUSTY SPRINGFIELD, SPOOKY, 00970006
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4

Ejemplo de la lista de reproducción:
Sintáxis: [ Descargar ] [ Ocultar ]
Using xml Syntax Highlighting
  1. <?xml version="1.0" encoding="ISO-8859-1"?>
  2. <PLAYLISTS>
  3. <PLAYLIST canal="1" nombrecanal=" 301 (SAT) SOLO MUSICA" web="0">
  4. <CANCION fecha="04/09/2012 00:00:00" duracion="230" categ="0" interprete="PEDRO JAVIER GONZALEZ" titulo="MASSACHUSSETS">/home/musicam/ogg/01136508.ogg</CANCION>
  5. <CANCION fecha="04/09/2012 00:02:30" duracion="621" categ="0" interprete="KENNY G" titulo="PERUVIAN NIGHTS">/home/musicam/ogg/01535306.ogg</CANCION>
  6. <CANCION fecha="04/09/2012 00:08:46" duracion="35" categ="0" interprete="FRANCIS WHITE" titulo="THE BREEZE AND I">/home/musicam/ogg/02001311.ogg</CANCION>
  7. <CANCION fecha="04/09/2012 00:11:51" duracion="347" categ="0" interprete="101 STRINGS" titulo="ORQUIDEAS A LA LUZ DE LA LUNA">/home/musicam/ogg/02002603.ogg</CANCION>
  8. <CANCION fecha="04/09/2012 00:15:38" duracion="129" categ="0" interprete="ENNIO MORRICONE" titulo="BROTHERS">/home/musicam/ogg/00712805.ogg</CANCION>
  9. </PLAYLIST>
  10. <PLAYLIST canal="2" nombrecanal=" 302 (SAT) SELECCIONES MUSICALES" web="0">
  11. <CANCION fecha="04/09/2012 00:00:00" duracion="324" categ="0" interprete="SERGIO RIVERO" titulo="LA LLAVE DE TU CORAZON">/home/musicam/ogg/01320604.ogg</CANCION>
  12. <CANCION fecha="04/09/2012 00:03:24" duracion="316" categ="0" interprete="BOB SINCLAR/STEVE EDWARDS" titulo="WORLD, HOLD ON">/home/musicam/ogg/01366701.ogg</CANCION>
  13. <CANCION fecha="04/09/2012 00:06:40" duracion="349" categ="0" interprete="BEN S BROTHER" titulo="LET ME OUT">/home/musicam/ogg/01502101.ogg</CANCION>
  14. </PLAYLIST>
  15. </PLAYLISTS>
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
dmon_30
Perlero nuevo
Perlero nuevo
 
Mensajes: 2
Registrado: 2012-09-08 10:50 @493

Publicidad

Re: como pasar consulta sql a xml predefinido

Notapor explorer » 2012-09-10 14:01 @626

Bienvenido a los foros de Perl en Español, dmon_30.

XML::Simple sirve muy bien para generar estructuras sencillas de XML.
Pero si la estructura es más complicada, es mejor usar algún otro.

Con el siguiente programa
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/env perl
  2. use XML::Simple;
  3.  
  4. my $xs  = XML::Simple->new();
  5. my $xml = {
  6.     PLAYLIST => [
  7.         {   canal       => 1,
  8.             nombrecanal => ' 301 (SAT) SOLO MUSICA',
  9.             web         => 0,
  10.             CANCION     => [
  11.                 {   fecha      => "04/09/2012 00:00:00",
  12.                     duracion   => 230,
  13.                     categ      => 0,
  14.                     interprete => "PEDRO JAVIER GONZALEZ",
  15.                     titulo     => "MASSACHUSSETS",
  16.                     content    => '/home/musicam/ogg/01136508.ogg'
  17.                 },
  18.                 {   fecha      => "04/09/2012 00:02:30",
  19.                     duracion   => 621,
  20.                     categ      => 0,
  21.                     interprete => "KENNY G",
  22.                     titulo     => "PERUVIAN NIGHTS",
  23.                     content    => '/home/musicam/ogg/01535306.ogg'
  24.                 },
  25.                 {   fecha      => "04/09/2012 00:08:46",
  26.                     duracion   => 35,
  27.                     categ      => 0,
  28.                     interprete => "FRANCIS WHITE",
  29.                     titulo     => "THE BREEZE AND I",
  30.                     content    => '/home/musicam/ogg/02001311.ogg'
  31.                 },
  32.                 {   fecha      => "04/09/2012 00:11:51",
  33.                     duracion   => 347,
  34.                     categ      => 0,
  35.                     interprete => "101 STRINGS",
  36.                     titulo     => "ORQUIDEAS A LA LUZ DE LA LUNA",
  37.                     content    => '/home/musicam/ogg/02002603.ogg'
  38.                 },
  39.                 {   fecha      => "04/09/2012 00:15:38",
  40.                     duracion   => 129,
  41.                     categ      => 0,
  42.                     interprete => "ENNIO MORRICONE",
  43.                     titulo     => "BROTHERS",
  44.                     content    => '/home/musicam/ogg/00712805.ogg'
  45.                 },
  46.             ],
  47.         },
  48.         {   canal       => 2,
  49.             nombrecanal => ' 302 (SAT) SELECCIONES MUSICALES',
  50.             web         => 0,
  51.             CANCION     => [
  52.                 {   fecha      => "04/09/2012 00:00:00",
  53.                     duracion   => 324,
  54.                     categ      => 0,
  55.                     interprete => "SERGIO RIVERO",
  56.                     titulo     => "LA LLAVE DE TU CORAZON",
  57.                     content    => '/home/musicam/ogg/01320604.ogg'
  58.                 },
  59.                 {   fecha      => "04/09/2012 00:03:24",
  60.                     duracion   => 316,
  61.                     categ      => 0,
  62.                     interprete => "BOB SINCLAR/STEVE EDWARDS",
  63.                     titulo     => "WORLD, HOLD ON",
  64.                     content    => '/home/musicam/ogg/01366701.ogg'
  65.                 },
  66.                 {   fecha      => "04/09/2012 00:06:40",
  67.                     duracion   => 349,
  68.                     categ      => 0,
  69.                     interprete => "BEN S BROTHER",
  70.                     titulo     => "LET ME OUT",
  71.                     content    => '/home/musicam/ogg/01502101.ogg'
  72.                 },
  73.             ],
  74.         },
  75.     ],
  76. };
  77.  
  78. print $xs->XMLout(
  79.     $xml,
  80.     RootName => 'PLAYLISTS',
  81.     XMLDecl  => '<?xml version="1.0" encoding="ISO-8859-1"?>',
  82. );
  83.  
  84. __END__
  85.  
Coloreado en 0.002 segundos, usando GeSHi 1.0.8.4
sale:
Sintáxis: [ Descargar ] [ Ocultar ]
Using xml Syntax Highlighting
  1. <?xml version="1.0" encoding="ISO-8859-1"?>
  2. <PLAYLISTS>
  3.   <PLAYLIST canal="1" nombrecanal=" 301 (SAT) SOLO MUSICA" web="0">
  4.     <CANCION categ="0" duracion="230" fecha="04/09/2012 00:00:00" interprete="PEDRO JAVIER GONZALEZ" titulo="MASSACHUSSETS">/home/musicam/ogg/01136508.ogg</CANCION>
  5.     <CANCION categ="0" duracion="621" fecha="04/09/2012 00:02:30" interprete="KENNY G" titulo="PERUVIAN NIGHTS">/home/musicam/ogg/01535306.ogg</CANCION>
  6.     <CANCION categ="0" duracion="35" fecha="04/09/2012 00:08:46" interprete="FRANCIS WHITE" titulo="THE BREEZE AND I">/home/musicam/ogg/02001311.ogg</CANCION>
  7.     <CANCION categ="0" duracion="347" fecha="04/09/2012 00:11:51" interprete="101 STRINGS" titulo="ORQUIDEAS A LA LUZ DE LA LUNA">/home/musicam/ogg/02002603.ogg</CANCION>
  8.     <CANCION categ="0" duracion="129" fecha="04/09/2012 00:15:38" interprete="ENNIO MORRICONE" titulo="BROTHERS">/home/musicam/ogg/00712805.ogg</CANCION>
  9.   </PLAYLIST>
  10.   <PLAYLIST canal="2" nombrecanal=" 302 (SAT) SELECCIONES MUSICALES" web="0">
  11.     <CANCION categ="0" duracion="324" fecha="04/09/2012 00:00:00" interprete="SERGIO RIVERO" titulo="LA LLAVE DE TU CORAZON">/home/musicam/ogg/01320604.ogg</CANCION>
  12.     <CANCION categ="0" duracion="316" fecha="04/09/2012 00:03:24" interprete="BOB SINCLAR/STEVE EDWARDS" titulo="WORLD, HOLD ON">/home/musicam/ogg/01366701.ogg</CANCION>
  13.     <CANCION categ="0" duracion="349" fecha="04/09/2012 00:06:40" interprete="BEN S BROTHER" titulo="LET ME OUT">/home/musicam/ogg/01502101.ogg</CANCION>
  14.   </PLAYLIST>
  15. </PLAYLISTS>
  16.  
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4

que sigue el esquema propuesto. Lo único que tienes que hacer es crear una estructura $xml como la mostrada a partir de los datos de la base de datos.
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14477
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Pasar consulta SQL a XML predefinido

Notapor dmon_30 » 2012-09-10 15:59 @707

Hola, explorer.

Gracias por la pronta respuesta, pero me surgen más dudas acerca de la utilización del módulo XML::Simple.

Según pones en el código necesitamos tantas estructuras...
Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
CANCION     => [
                {   fecha      => "04/09/2012 00:00:00",
                    duracion   => 230,
                    categ      => 0,
                    interprete => "PEDRO JAVIER GONZALEZ",
                    titulo     => "MASSACHUSSETS",
                    content    => '/home/musicam/ogg/01136508.ogg'
                },
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4

como canciones tengamos en cada canal, pero estas playlist aun siendo para 24 horas, no siempre son justas y pueden entrar más o menos canciones. ¿Cómo sé cuántas estructuras para canción tengo que colocar, si éstas pueden variar?

Por otro lado en la estructura ...
Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
PLAYLIST => [
        {   canal       => 1,
            nombrecanal => ' 301 (SAT) SOLO MUSICA',
            web         => 0,
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4

tenemos unos 70 canales distintos y tiene que aparecer solo al principio de cada canal y luego las canciones de esta forma:
<?xml version="1.0" encoding="ISO-8859-1"?>
<PLAYLISTS>
<PLAYLIST canal="1" nombrecanal=" 301 (SAT) SOLO MUSICA" web="0">
<CANCION fecha="04/09/2012 00:00:00" duracion="230" categ="0" interprete="PEDRO JAVIER GONZALEZ" titulo="MASSACHUSSETS">/home/musicam/ogg/01136508.ogg</CANCION>
<CANCION fecha="04/09/2012 23:58:26" duracion="40" categ="0" interprete="PEDRO JAVIER GONZALEZ" titulo="THE LOGICAL SONG">/home/musicam/ogg/00234208.ogg</CANCION>
</PLAYLIST>
<PLAYLIST canal="2" nombrecanal=" 302 (SAT) SELECCIONES MUSICALES" web="0">
<CANCION fecha="04/09/2012 00:00:00" duracion="324" categ="0" interprete="SERGIO RIVERO" titulo="LA LLAVE DE TU CORAZON">/home/musicam/ogg/01320604.ogg</CANCION>
<CANCION fecha="04/09/2012 23:59:00" duracion="338" categ="0" interprete="SHAILA DURCAL" titulo="TARDE">/home/musicam/ogg/01439110.ogg</CANCION>
</PLAYLIST>
</PLAYLISTS>

De nuevo, muchas gracias, por tu ayuda.

Un saludo.
dmon_30
Perlero nuevo
Perlero nuevo
 
Mensajes: 2
Registrado: 2012-09-08 10:50 @493

Re: Pasar consulta SQL a XML predefinido

Notapor explorer » 2012-09-10 16:19 @721

dmon_30 escribiste:Gracias por la pronta respuesta, pero me surgen más dudas acerca de la utilización del módulo XML::Simple.
Por las dudas que pones, más bien son dudas relativas a la creación de la estructura.

dmon_30 escribiste:Según pones en el código necesitamos tantas estructuras...
Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
CANCION     => [
                {   fecha      => "04/09/2012 00:00:00",
                    duracion   => 230,
                    categ      => 0,
                    interprete => "PEDRO JAVIER GONZALEZ",
                    titulo     => "MASSACHUSSETS",
                    content    => '/home/musicam/ogg/01136508.ogg'
                },
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4

como canciones tengamos en cada canal, pero estas playlist aun siendo para 24 horas, no siempre son justas y pueden entrar más o menos canciones. ¿Cómo sé cuántas estructuras para canción tengo que colocar, si éstas pueden variar?
No necesitas conocerlo. Simplemente vas haciendo un push() al array que va almacenando las canciones, a medida de que las vayas leyendo desde la base de datos.

(Pssst... estamos en el foro Intermedio ;) )

dmon_30 escribiste:Por otro lado en la estructura ...
Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
PLAYLIST => [
        {   canal       => 1,
            nombrecanal => ' 301 (SAT) SOLO MUSICA',
            web         => 0,
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4

tenemos unos 70 canales distintos y tiene que aparecer solo al principio de cada canal y luego las canciones de esta forma:
Yo creo que mi ejemplo reproduce el mismo esquema: el raíz es PLAYLISTS, que contiene un conjunto de PLAYLIST, y cada uno contiene un conjunto de CANCIONes.

La forma de crear las PLAYLIST es lo mismo que las CANCIONes: por medio de push() podemos ir agregando elementos a un array anónimo, o incluso ir creciendo la estructura a medida de que la vamos leyendo de la base de datos.

Como la base de datos que pusiste de ejemplo no muestra claramente cómo crear el XML de salida, no puedo darte más pistas (en concreto, no veo la forma de cómo diferenciar a unos canales de otros).
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14477
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España


Volver a Intermedio

¿Quién está conectado?

Usuarios navegando por este Foro: No hay usuarios registrados visitando el Foro y 4 invitados