• Publicidad

Pregunta sobre XML y Perl

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

Pregunta sobre XML y Perl

Notapor caribesoft » 2006-11-14 11:47 @532

Hola Amigos Perlianos :

Estoy batallando un poquito al tratar de recibir datos en XML dentro de un script en Perl y estoy un poco confundido.

Estoy utilizando XML::Simple, con la instrucción XLMin();

Mi Script es el siguiente :

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
use strict;
print "Content-type:text/html\n\n";
use XML::Simple;

$xml = new XML::Simple ();
$reservas = $xml->XMLin();

      $action    = $reservas->{action};
      $propid    = $reservas->{PropertyID};
      $propname  = $reservas->{PropertyName};
      $chaincode = $reservas->{ChainCode};

# ... y asi sucesivamente armo la estructura de datos para Perl.
 
Coloreado en 0.004 segundos, usando GeSHi 1.0.8.4


Esta es la estructura de datos que me envian :

Sintáxis: [ Descargar ] [ Ocultar ]
Using xml Syntax Highlighting
<?xml version='1.0'?>
<gkxml>
 <export_version>0.7</export_version>
 <export_type>travelly</export_type>
 <export_date>20061113</export_date>
 <action>newres</action>
 <GroupID id='travelly'>
  <GroupName>Omega</GroupName>
  <ChainCode id='Delta'>
   <ChainName>Delta Hotels</ChainName>
   <PropertyID id='KJG6689'>
    <PropertyName>Omega Spa Resort</PropertyName>
    <PropertyExtID></PropertyExtID>
    <AgentID id='1'>
     <AgentCode>DIRECT</AgentCode>
     <AgentIATA>DIREC</AgentIATA>
     <AgentCTA>Direct Client</AgentCTA>
     <AffiliateAgentCode>delta</AffiliateAgentCode>
     <GuestReservationDetails>
      <GuestID id='2507'>
       <PNR>2507</PNR>
       <Title>Mr.</Title>
       <FirstName>Trent</FirstName>
       <LastName>Zagorsky</LastName>
       <Address>8385 Frederick Court </Address>
       <City>De Soto</City>
       <ProvState>ks</ProvState>
       <Country>United States</Country>
       <PostcodeZip>66018</PostcodeZip>
       <Telephone>9139098299</Telephone>
       <Fax></Fax>
       <Email>[email protected]</Email>
       <CompanyName></CompanyName>
       <Nationality></Nationality>
       <PassportNumber></PassportNumber>
       <MembershipNumber></MembershipNumber>
       <Membership></Membership>
       <MailingList>yes</MailingList>
       <Language>en</Language>
       <ReservationID id='3373'>
        <ReservationNumber>GK3373</ReservationNumber>
        <ReservationStatus>Confirmed On-Line</ReservationStatus>
        <ArriveDate>20070125</ArriveDate>
        <DepartDate>20070130</DepartDate>
        <RateCode>KRGVJRS</RateCode>
        <RateCodeName>Jacuzzi Jr. Suite</RateCodeName>
        <RateCodeType>Internet Rate</RateCodeType>
        <RoomClass>Junior Suite</RoomClass>
        <NumberRooms>1</NumberRooms>
        <NumberOfNights>5</NumberOfNights>
        <Currency>USD</Currency>
        <RoomCost>2000</RoomCost>
        <TaxType>included</TaxType>
        <GuestNames>Zagorsky, Mr. Trent</GuestNames>
        <Adults>2</Adults>
        <Children>0</Children>
        <Infants>0</Infants>
        <RoomPreference>Double</RoomPreference>
        <SmokingPreference>Non Smoking</SmokingPreference>
        <Comments></Comments>
        <ArriveMode>Air</ArriveMode>
        <ArriveDetails>Frontier #46 arrive 10:40am</ArriveDetails>
        <ArriveTransfer>no</ArriveTransfer>
        <DepartureMode></DepartureMode>
        <DepartureDetails></DepartureDetails>
        <DepartureTransfer>no</DepartureTransfer>
        <RateInclusions>Gourmet Inclusive features: All meals, unlimited domestic & selected intl. premium alcoholic & non-alcoholic drinks, day/night activity program, non motorized watersports, scuba diving clinic in pool, live music & shows, use of bicycles, fitness center, sauna & steam room, day/night tennis, room service, in room minibar replenished daily, welcome glass of sparkling wine, all taxes & gratuities. </RateInclusions>
       <SpecialDates></SpecialDates>
       <ReservationEntered>2006-11-13 22:24:57</ReservationEntered>
      </ReservationID>
     </GuestID>
     <AgentMessage></AgentMessage>
     <Currency>USD</Currency>
     <BookingAmount>2000</BookingAmount>
     <DepositPaid>200.00</DepositPaid>
     <DepositPaidDate>20061113</DepositPaidDate>
     <RemainderAmount>1800</RemainderAmount>
     <RemainderDueDate>20061115</RemainderDueDate>
     <PaymentGateway>YOURPAY</PaymentGateway>
     <PaymentTransactionID>48800FC3-455937</PaymentTransactionID>
    </GuestReservationDetails>
   </AgentID>
  </PropertyID>
 </ChainCode>
</GroupID>
</gkxml>
Coloreado en 0.003 segundos, usando GeSHi 1.0.8.4


Aparentemente sólo recibo el campo <action>newres</action> que queda almacenado en $action.

Mi pregunta es, ¿ cómo debería de estructurar la info, porque como verán tiene varias etiquetas de grupo ?

De antemano, muchas gracias por su atención,

Caribesoft
caribesoft
Perlero nuevo
Perlero nuevo
 
Mensajes: 73
Registrado: 2006-05-09 22:01 @959
Ubicación: Cancun

Publicidad

Notapor kidd » 2006-11-14 13:24 @600

Hola:

El primer problema que tienes es que dentro del tag <RateInclusions> tienes los caracteres & que son caracteres especiales y que debes de cambiar por &amp;.

Después de hacer esto ya puedes hacer el parseo de tu XML sin problema y obtendrás un estructura similar a la siguiente:

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
$VAR1 = {
          'export_date' => '20061113',
          'action' => 'newres',
          'export_type' => 'travelly',
          'export_version' => '0.7',
          'GroupID' => {
                       'GroupName' => 'Omega',
                       'id' => 'travelly',
                       'ChainCode' => {
                                      'PropertyID' => {
                                                      'AgentID' => {
                                                                   'AgentIATA' => 'DIREC',
                                                                   'AffiliateAgentCode' => 'delta',
                                                                   'id' => '1',
                                                                   'AgentCTA' => 'Direct Client',
                                                                   'AgentCode' => 'DIRECT',
                                                                   'GuestReservationDetails' => {
                                                                                                'RemainderDueDate' => '20061115',
                                                                                                'BookingAmount' => '2000',
                                                                                                'GuestID' => {
                                                                                                             'FirstName' => 'Trent',
                                                                                                             'Address' => '8385 Frederick Court ',
                                                                                                             'MembershipNumber' => {},
                                                                                                             'City' => 'De Soto',
                                                                                                             'Title' => 'Mr.',
                                                                                                             'PassportNumber' => {},
                                                                                                             'LastName' => 'Zagorsky',
                                                                                                             'id' => '2507',
                                                                                                             'Email' => 'tzagorsky\\@kc.rr.com',
                                                                                                             'PNR' => '2507',
                                                                                                             'Language' => 'en',
                                                                                                             'Nationality' => {},
                                                                                                             'ReservationID' => {
                                                                                                                                'Comments' => {},
                                                                                                                                'RateCodeType' => 'Internet Rate',
                                                                                                                                'NumberOfNights' => '5',
                                                                                                                                'Infants' => '0',
                                                                                                                                'Children' => '0',
                                                                                                                                'ArriveDate' => '20070125',
                                                                                                                                'RateInclusions' => 'Gourmet Inclusive features: All meals, unlimited domestic & selected intl. premium alcoholic & non-alcoholic drinks, day/night activity program, non motorized watersports, scuba diving clinic in pool, live music & shows, use of bicycles, fitness center, sauna & steam room, day/night tennis, room service, in room minibar replenished daily, welcome glass of sparkling wine, all taxes & gratuities.',
                                                                                                                                'RateCode' => 'KRGVJRS',
                                                                                                                                'GuestNames' => 'Zagorsky, Mr. Trent',
                                                                                                                                'TaxType' => 'included',
                                                                                                                                'Adults' => '2',
                                                                                                                                'RoomClass' => 'Junior Suite',
                                                                                                                                'id' => '3373',
                                                                                                                                'ArriveTransfer' => 'no',
                                                                                                                                'DepartureTransfer' => 'no',
                                                                                                                                'RateCodeName' => 'Jacuzzi Jr. Suite',
                                                                                                                                'DepartureMode' => {},
                                                                                                                                'ArriveDetails' => 'Frontier #46 arrive 10:40am',
                                                                                                                                'DepartureDetails' => {},
                                                                                                                                'SmokingPreference' => 'Non Smoking',
                                                                                                                                'SpecialDates' => {},
                                                                                                                                'ReservationEntered' => '2006-11-13 22:24:57',
                                                                                                                                'ReservationNumber' => 'GK3373',
                                                                                                                                'NumberRooms' => '1',
                                                                                                                                'Currency' => 'USD',
                                                                                                                                'RoomCost' => '2000',
                                                                                                                                'DepartDate' => '20070130',
                                                                                                                                'ReservationStatus' => 'Confirmed On-Line',
                                                                                                                                'ArriveMode' => 'Air',
                                                                                                                                'RoomPreference' => 'Double'
                                                                                                                              },
                                                                                                             'Telephone' => '9139098299',
                                                                                                             'Membership' => {},
                                                                                                             'ProvState' => 'ks',
                                                                                                             'MailingList' => 'yes',
                                                                                                             'Country' => 'United States',
                                                                                                             'PostcodeZip' => '66018',
                                                                                                             'CompanyName' => {},
                                                                                                             'Fax' => {}
                                                                                                           },
                                                                                                'DepositPaid' => '200.00',
                                                                                                'PaymentTransactionID' => '48800FC3-455937',
                                                                                                'AgentMessage' => {},
                                                                                                'Currency' => 'USD',
                                                                                                'PaymentGateway' => 'YOURPAY',
                                                                                                'DepositPaidDate' => '20061113',
                                                                                                'RemainderAmount' => '1800'
                                                                                              }
                                                                 },
                                                      'id' => 'KJG6689',
                                                      'PropertyExtID' => {},
                                                      'PropertyName' => 'Omega Spa Resort'
                                                    },
                                      'ChainName' => 'Delta Hotels',
                                      'id' => 'Delta'
                                    }
                     }
        };
Coloreado en 0.006 segundos, usando GeSHi 1.0.8.4


Ya con eso podrás ver cómo trabajar con tu variable que en realidad es una referencia a un hash.


Saludos
Uriel Lizama Perl programmer fundador de Perl en Español
Perl Programming Language
Avatar de Usuario
kidd
Creador de Perl en Español
Creador de Perl en Español
 
Mensajes: 1166
Registrado: 2003-10-15 16:52 @744
Ubicación: México

Gracias ...

Notapor caribesoft » 2006-11-14 13:57 @623

Como siempre muchas gracias Kidd :

Pero perdón por mi ignorancia. ¿Cuál sería la mejor forma de hacer la substitución de los caracteres & por &amp;?, ¿sería así? :

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
$VAR1 =~ s/&/&amp/
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4


¿¿¿o es una locura ???

saludos,

Caribesoft
caribesoft
Perlero nuevo
Perlero nuevo
 
Mensajes: 73
Registrado: 2006-05-09 22:01 @959
Ubicación: Cancun

Notapor kidd » 2006-11-14 15:59 @708

Hola:

Pues si lo tienes en un string si podrías hacer eso:

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
$VAR =~ s/\&/\&amp;/g;
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4


Ahora, lo mejor sería corregir el problema desde la raíz, es decir en el archivo XML.


Saludos
Uriel Lizama Perl programmer fundador de Perl en Español
Perl Programming Language
Avatar de Usuario
kidd
Creador de Perl en Español
Creador de Perl en Español
 
Mensajes: 1166
Registrado: 2003-10-15 16:52 @744
Ubicación: México

Tienes razon

Notapor caribesoft » 2006-11-16 17:06 @754

Hola Kidd :

Tienes razon, el problema viene desde el XML, no es un archivo sino que llega a traves de un POST.
Mi pregunta es :

1. La persona que me esta enviando el POST deberia de corregir su programa que no acepte los simbolos & para formar el XML no crees ?, ya que en realidad genera un error :
Código: Seleccionar todo
not well-formed (invalid token)
 


2. Conoces alguna forma de poder corregir este POST al momento de recibirlo, he estado probando varias cosas, como del "Subtituir" pero no me funciona .

Los tips son bienvenidos,

Muchas gracias,

Caribesoft
caribesoft
Perlero nuevo
Perlero nuevo
 
Mensajes: 73
Registrado: 2006-05-09 22:01 @959
Ubicación: Cancun

Notapor kidd » 2006-11-16 18:40 @819

Hola:

Si te está mandando un post en una sola variable, entonces tu problema puede estar en los newlines, para ello usa un expresión como la siguiente:

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
$VAR =~ s/\&/\&amp;/mg;
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4


Para mayores detalles acerca de los Regexp en Perl, pues checar en los tutoriales del sitio:
http://perlenespanol.com/tutoriales/exp ... index.html


Saludps
Uriel Lizama Perl programmer fundador de Perl en Español
Perl Programming Language
Avatar de Usuario
kidd
Creador de Perl en Español
Creador de Perl en Español
 
Mensajes: 1166
Registrado: 2003-10-15 16:52 @744
Ubicación: México


Volver a Intermedio

¿Quién está conectado?

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