• Jueves 28 de Marzo de 2024, 22:50

Autor Tema:  Capturando Xml En C Cpn La Libxml  (Leído 2056 veces)

pandemolde

  • Nuevo Miembro
  • *
  • Mensajes: 13
    • Ver Perfil
Capturando Xml En C Cpn La Libxml
« en: Viernes 5 de Agosto de 2005, 16:56 »
0
Muy buenas. Estoy realizando una aplicación en C para recoger el contenido del documento XML utilizando la libreria libxml. El problema que me ha surgido es que a la hora de recoger los nombres de los tags lo hago con la función xmlTextReaderName(reader) y dicha función te pone el nombre de los tags 2 veces, una por el de apertura y otra por el de cierre. ¿Alguien conoce una función que yo pueda utilizar para que me lo recoja una sola vez o he de fabricármela? un saludo muy fuerte y gracias por anticipado!!!

nicokiki

  • Miembro MUY activo
  • ***
  • Mensajes: 298
    • Ver Perfil
Re: Capturando Xml En C Cpn La Libxml
« Respuesta #1 en: Domingo 7 de Agosto de 2005, 18:50 »
0
Hola!!!

Mira, hace unos meses q no programo en C/C++ pero encontre un ejemplo de uso de libxml2 (bajo Linux) y te lo mando. La verdad es q la funcion q decis no la use, por eso te paso el ejemplo de lo q hice para q t sirva de ayuda en algo:

Antes q nada, perdon por los q lean esto tan largo y por los errores q pude haber hecho y por el coding style q no me gustaaaa

<code>
#include "CXMLParserServidor.h"

//******************************************************
// Constructor de la clase CXMLParserServidor
//******************************************************
CXMLParserServidor::CXMLParserServidor()
{
}

//******************************************************
// Getea el atributo Comando
//******************************************************
CComando* CXMLParserServidor::getComando() const
{
  return this->Comando;
}

//******************************************************
// Setea el atributo Comando
//******************************************************
void CXMLParserServidor::setComando(CComando* Comando)
{
  this->Comando = Comando;
}

//******************************************************
// Parsea un string y lo setea en el atributo Comando
//******************************************************
void CXMLParserServidor::ParsearString(TString StringAParsear)
{
  int LongitudAParsear = StringAParsear.size();
  xmlDocPtr  Documento;
  xmlNodePtr NodoActual;

  // Obtengo el documento a parsear en formato string
  Documento = xmlParseMemory(StringAParsear.c_str(), LongitudAParsear);

  if (Documento == NULL)
  {
    cout << "Documento = null" << endl;
    return;
  }

  // Obtengo el nodo raiz
  NodoActual = xmlDocGetRootElement(Documento);

  if (NodoActual == NULL)
  {
    cout << "NodoActual = null" << endl;
    return;
  }

  // Verifico que el primer nodo sea correcto para el caso en particular
  if (xmlStrcmp(NodoActual->name, (const xmlChar *) "MENSAJE"))
  {
    cout << "El documento no es correcto" << endl;
    xmlFreeDoc(Documento);
    return;
  }

  // Obtengo el nodo hijo del raiz
  NodoActual = NodoActual->children;

  while (NodoActual != NULL)
  {
    // Parseo los Nodos
    parsearNodos(NodoActual);

    NodoActual = NodoActual->next;
  }

  cout << "Termine de parsear" << endl;

  // Libero el documento
  xmlFreeDoc(Documento);
  xmlFreeNode(NodoActual);
  return;
}

//******************************************************
// Parsea los nodos hijos del tag <MENSAJE>
//******************************************************
void CXMLParserServidor::parsearNodos(xmlNodePtr NodoActual)
{
  if (!xmlStrcmp(NodoActual->name, (const xmlChar *) "NOMBREARCHIVOBUSCADO"))
  {
    // Aca leo el contenido del XML del tag <COMANDO> y lo cargo
    // en el atributo Comando
    this->Comando->setNombreArchivoBuscado(getNombreArchivoBuscado(NodoActual));
  }
  if (!xmlStrcmp(NodoActual->name, (const xmlChar *) "COMANDO"))
  {
    // Aca leo el contenido del XML del tag <COMANDO> y lo cargo
    // en el atributo Comando
    getComandoDelXML(NodoActual);
  }
  if (!xmlStrcmp(NodoActual->name, (const xmlChar *) "NOMBRE"))
  {
    // Aca leo el contenido del XML del tag <NOMBRE> y lo cargo
    // en el atributo Comando
    this->Comando->setNombre(this->getNombreDelXML(NodoActual));
  }
  if (!xmlStrcmp(NodoActual->name, (const xmlChar *) "APELLIDO"))
  {
    // Aca leo el contenido del XML del tag <APELLIDO> y lo cargo
    // en el atributo Comando
    this->Comando->setApellido(this->getApellidoDelXML(NodoActual));
  }
  if (!xmlStrcmp(NodoActual->name, (const xmlChar *) "NICK"))
  {
    // Aca leo el contenido del XML del tag <NICK> y lo cargo
    // en el atributo Comando
    this->Comando->setNick(this->getNickDelXML(NodoActual));
  }
  if (!xmlStrcmp(NodoActual->name, (const xmlChar *) "PASSWORD"))
  {
    // Aca leo el contenido del XML del tag <PASSWORD> y lo cargo
    // en el atributo Comando
    this->Comando->setPassword(this->getPasswordDelXML(NodoActual));
  }
  if (!xmlStrcmp(NodoActual->name, (const xmlChar *) "CLAVE"))
  {
    // Aca leo el contenido del XML del tag <CLAVE> y lo cargo
    // en el atributo Comando
    this->Comando->setClave(this->getClaveDelXML(NodoActual));
  }
  if (!xmlStrcmp(NodoActual->name, (const xmlChar *) "ID"))
  {
    // Aca leo el contenido del XML del tag <COMANDO> y lo cargo
    // en el atributo Comando
    this->Comando->setIdUsuario(this->getIdDelXML(NodoActual));
  }
  if (!xmlStrcmp(NodoActual->name, (const xmlChar *) "IDUSUARIOBUSCADO"))
  {
    // Aca leo el contenido del XML del tag <COMANDO> y lo cargo
    // en el atributo Comando
    this->Comando->setIdUsuarioBuscado(this->getIdUsuarioBuscadoDelXML(NodoActual));
  }
  if (!xmlStrcmp(NodoActual->name, (const xmlChar *) "LISTADEARCHIVOS"))
  {
    // Entro un nivel, al nivel del tag <LISTADEARCHIVOS>
    xmlNodePtr NodoActualListaDeArchivos;
    NodoActualListaDeArchivos = NodoActual->children;

    while (NodoActualListaDeArchivos != NULL)
    {
      // Aca recorro por lo q esta dentro del tag <LISTADEARCHIVOS>
      // Comienzo a meterme otro nivel, el cual comienza en este tag
      parsearListaDeArchivos(NodoActualListaDeArchivos);

      NodoActualListaDeArchivos = NodoActualListaDeArchivos->next;
    }
    xmlFreeNode(NodoActualListaDeArchivos);
  }
  if (!xmlStrcmp(NodoActual->name, (const xmlChar *) "LISTADEPALABRAS"))
  {
    xmlNodePtr NodoActualListaDePalabras;
    NodoActualListaDePalabras = NodoActual->children;
    // Entro un nivel, al nivel del tag <LISTADEPALABRAS>

    while (NodoActualListaDePalabras != NULL)
    {
      // Aca recorro por lo q esta dentro del tag <LISTADEPALABRAS>
      // Comienzo a meterme otro nivel, el cual comienza en este tag
      parsearListaDePalabras(NodoActualListaDePalabras);

      NodoActualListaDePalabras = NodoActualListaDePalabras->next;
    }
    xmlFreeNode(NodoActualListaDePalabras);
  }
}

//******************************************************
// Parsea el tag <LISTADEARCHIVOS>
//******************************************************
void CXMLParserServidor::parsearListaDeArchivos(xmlNodePtr NodoActual)
{
  if (!xmlStrcmp(NodoActual->name, (const xmlChar *) "ARCHIVO"))
  {
    // Aca leo el contenido del XML del tag <ARCHIVO> y lo cargo
    // en el atributo Comando
    this->Comando->agregarNodoListaDeArchivos(this->getArchivoDelXML(NodoActual));
  }
}

//******************************************************
// Parsea el tag <LISTADEPALABRAS>
//******************************************************
void CXMLParserServidor::parsearListaDePalabras(xmlNodePtr NodoActual)
{
  if (!xmlStrcmp(NodoActual->name, (const xmlChar *) "PALABRA"))
  {
    // Aca leo el contenido del XML del tag <PALABRA> y lo cargo
    // en el atributo Comando
    getPalabraDelXML(NodoActual);
  }
}

//******************************************************
// Parsea el tag <COMANDO>
//******************************************************
void CXMLParserServidor::getComandoDelXML(xmlNodePtr NodoActual)
{
  xmlChar* Contenido;
  xmlAttr* Atributo;

  // Obtengo el puntero a atributos del nodo actual
  Atributo = (xmlAttr *)NodoActual->properties;

  // Recorro los atributos del tag <COMANDO>
  while (Atributo != NULL)
  {
    if (!xmlStrcmp(Atributo->name, (const xmlChar *) "VALOR"))
    {
      // Obtengo la propiedad Valor del presente tag
      Contenido = xmlGetProp(NodoActual, Atributo->name);

      this->Comando->setComando((char*)(Contenido));
      xmlFree(Contenido);
    }

    Atributo = Atributo->next;
  }

  // Libero el puntero a Atributo
  xmlFreeProp(Atributo);
}

//******************************************************
// Parsea el tag <PALABRA>
//******************************************************
void CXMLParserServidor::getPalabraDelXML(xmlNodePtr NodoActual)
{
  xmlChar* Contenido;

  // Obtengo el contenido del presente tag
  Contenido = xmlNodeGetContent(NodoActual);

  this->Comando->agregarPalabraListaDePalabras((char*)(Contenido));
  xmlFree(Contenido);
}

//******************************************************
// Escribe un XML en memoria (en un string de la STL)
// a partir de un CComando
//******************************************************
void CXMLParserServidor::ParsearComando()
{
  xmlDocPtr Documento;

  Documento = NuevoDocumento("MENSAJE");

  // Agrego los nodos que colgaran del tag <MENSAJE>
  AgregarNodos(Documento);

  xmlChar** buffer = (xmlChar**)xmlMemMalloc(sizeof(xmlChar*));
  int* x;
  // Guardo en memoria el XML
  xmlDocDumpMemoryEnc(Documento, buffer, x ,(const char *)("ISO-8859-1"));
  // Guardo en archivo el XML
  xmlSaveFile((const char*)("holahola.xml"), Documento);

  this->setStringParseo((char*)(*buffer));
}

//******************************************************
// Escribe el tag <COMANDO> en el XML
//******************************************************
void CXMLParserServidor::AgregarComando(xmlNodePtr NodoActual)
{
  xmlSetProp(NodoActual, (const xmlChar *)("VALOR"), (const xmlChar *)(this->Comando->getComando().c_str() ) );
}


//******************************************************
// Escribe el tag <CLAVE> en el XML
//******************************************************
void CXMLParserServidor::AgregarClave(xmlNodePtr NodoActual)
{
  xmlNodeAddContent(NodoActual, (const xmlChar *)(this->Comando->getClave().c_str() ));
}

//******************************************************
// Escribe el tag <LISTADEARCHIVOS> en el XML
//******************************************************
void CXMLParserServidor::AgregarListaDeArchivos(xmlNodePtr Nodo)
{
  for (int i = 0; i < (this->Comando->getListaDeArchivos().getLongitud()); i++)
  {
    xmlNodePtr NodoAux = xmlNewChild(Nodo, NULL, (const xmlChar *)("ARCHIVO"), NULL);

    // Agrego el tag <ARCHIVO>
    AgregarArchivo(NodoAux, i);
  }
}

//******************************************************
// Escribe el tag <LISTADEPALABRAS> en el XML
//******************************************************
void CXMLParserServidor::AgregarListaDePalabras(xmlNodePtr Nodo)
{
  for (int i = 0; i < (this->Comando->getListaDePalabras().getLongitud()); i++)
  {
    xmlNodePtr NodoAux = xmlNewChild(Nodo, NULL, (const xmlChar *)("PALABRA"), NULL);

    // Agrego el tag <PALABRA>
    AgregarPalabra(NodoAux, i);
  }
}

//******************************************************
// Escribe el tag <ARCHIVO> en el XML
//******************************************************
void CXMLParserServidor::AgregarArchivo(xmlNodePtr Nodo, int i)
{
  TString Operacion;
  xmlNodePtr NodoAltas;
  xmlNodePtr NodoAlta;
  xmlNodePtr NodoBajas;
  xmlNodePtr NodoBaja;
  xmlNodePtr NodoModificaciones;
  xmlNodePtr NodoModificacion;
  CNodoListaArchivos NodoLista =  (this->Comando->getListaDeArchivos().getNodoListaArchivos(i));

  //Tag <ATRIBUTOS>
  xmlNodePtr NodoAuxAtr = xmlNewChild(Nodo, NULL, (const xmlChar *)("ATRIBUTOS"), NULL);

  xmlChar* NormaString   = xmlXPathCastNumberToString(NodoLista.getArchivo().getNorma());
   
  xmlSetProp(NodoAuxAtr, (const xmlChar *)("NOMBRE"), (const xmlChar *)(NodoLista.getArchivo().getNombre().c_str() ) );
  xmlSetProp(NodoAuxAtr, (const xmlChar *)("TAMANIO"), (const xmlChar *)(NodoLista.getArchivo().getTamanio().c_str() ) );
  xmlSetProp(NodoAuxAtr, (const xmlChar *)("FECHAMODIF"), (const xmlChar *)(NodoLista.getArchivo().getFechaModificacion().c_str() ) );
  xmlSetProp(NodoAuxAtr, (const xmlChar *)("NORMA"), (const xmlChar *)(NormaString) );
  //Fin tag <ATRIBUTOS>

  //Tag <OPERACION>
  xmlNodePtr NodoAux = xmlNewChild(Nodo, NULL, (const xmlChar *)("OPERACION"), NULL);

  switch (NodoLista.getOperacion())
  {
    case 'C': Operacion = "CREAR";          break;
    case 'E': Operacion = "ELIMINAR";       break;
    case 'M': Operacion = "ABMS";           break;
    case 'P': Operacion = "MODIFICAR";      break;
    case 'F': Operacion = "MODIFICARYABMS"; break;
    case 'N': Operacion = "NADA";           break;
    default :                               break;
  };

  xmlNodeAddContent(NodoAux, (const xmlChar *)(Operacion.c_str() ));
  //Fin tag <OPERACION>

  //Tag <ABM>
  if (NodoLista.tieneListasABM() == true)
  {
    xmlNodePtr NodoABM = xmlNewChild(Nodo, NULL, (const xmlChar *)("ABM"), NULL);

    if (NodoLista.getLongitudListaAltas() > 0)
    {
      CListaDeABM ListaA = NodoLista.getListaDeABMAltas();
      NodoAltas = xmlNewChild(NodoABM, NULL, (const xmlChar *)("ALTAS"), NULL);
      NodoAlta = xmlNewChild(NodoAltas, NULL, (const xmlChar *)("ALTA"), NULL);

      for (short j = 0; j < ListaA.getLongitud(); j++)
      {
        xmlSetProp(NodoAlta, (const xmlChar *)("PALABRA"), (const xmlChar *)(ListaA.getABM(j).getPalabra().c_str() ) );    
        xmlSetProp(NodoAlta, (const xmlChar *)("FRECUENCIA"), (const xmlChar *)(ListaA.getABM(j).getFrecuenciaString().c_str() ) );
      }
    }
    if (NodoLista.getLongitudListaBajas() > 0)
    {
      CListaDeABM ListaB = NodoLista.getListaDeABMBajas();
      NodoBajas = xmlNewChild(NodoABM, NULL, (const xmlChar *)("BAJAS"), NULL);
      NodoBaja = xmlNewChild(NodoBajas, NULL, (const xmlChar *)("BAJA"), NULL);

      for (short j = 0; j < ListaB.getLongitud(); j++)
      {
        xmlSetProp(NodoBaja, (const xmlChar *)("PALABRA"), (const xmlChar *)(ListaB.getABM(j).getPalabra().c_str() ) );
        xmlSetProp(NodoBaja, (const xmlChar *)("FRECUENCIA"), (const xmlChar *)(ListaB.getABM(j).getFrecuenciaString().c_str() ) );
      }
    }
    if (NodoLista.getLongitudListaModificaciones() > 0)
    {
      CListaDeABM ListaM = NodoLista.getListaDeABMModificaciones();
      NodoModificaciones = xmlNewChild(NodoABM, NULL, (const xmlChar *)("MODIFICACIONES"), NULL);
      NodoModificacion = xmlNewChild(NodoModificaciones, NULL, (const xmlChar *)("MODIFICACION"), NULL);

      for (short j = 0; j < ListaM.getLongitud(); j++)
      {
        xmlSetProp(NodoModificacion, (const xmlChar *)("PALABRA"), (const xmlChar *)(ListaM.getABM(j).getPalabra().c_str() ) );
        xmlSetProp(NodoModificacion, (const xmlChar *)("FRECUENCIA"), (const xmlChar *)(ListaM.getABM(j).getFrecuenciaString().c_str() ) );
      }
    }
   
  }
  //Fin tag <ABM>  


}

//******************************************************
// Escribe el tag <PALABRA> en el XML
//******************************************************
void CXMLParserServidor::AgregarPalabra(xmlNodePtr Nodo, int i)
{
  xmlNodeAddContent(Nodo, (const xmlChar *)(this->Comando->getListaDePalabras().getPalabra(i).c_str() ));
}

//******************************************************
// Agrego un los tags
//******************************************************
void CXMLParserServidor::AgregarNodos(xmlDocPtr Documento)
{
  xmlNodePtr Raiz;
  xmlNodePtr Nodo;

  // La raiz del documento se la asigno a Raiz
  Raiz = xmlDocGetRootElement(Documento);

  if (this->Comando->getNombreArchivoBuscado().size() > 0)
  {
    Nodo = xmlNewChild(Raiz, NULL, (const xmlChar *)("NOMBREARCHIVOBUSCADO"), NULL);
    AgregarNombreArchivoBuscado(Nodo, this->Comando->getNombreArchivoBuscado());
  }
  if (this->Comando->getComando().size() > 0)
  {
    Nodo = xmlNewChild(Raiz, NULL, (const xmlChar *)("COMANDO"), NULL);
    AgregarComando(Nodo);
  }
  if (this->Comando->getApellido().size() > 0)
  {
    Nodo = xmlNewChild(Raiz, NULL, (const xmlChar *)("APELLIDO"), NULL);
    AgregarApellido(Nodo, this->Comando->getApellido());
  }
  if (this->Comando->getClave().size() > 0)
  {
    Nodo = xmlNewChild(Raiz, NULL, (const xmlChar *)("CLAVE"), NULL);
    AgregarClave(Nodo);
  }
  if (this->Comando->getIdUsuario() > 0)
  {
    Nodo = xmlNewChild(Raiz, NULL, (const xmlChar *)("ID"), NULL);
    AgregarId(Nodo, this->Comando->getIdUsuario());
  }
  if (this->Comando->getIdUsuarioBuscado() > 0)
  {
    Nodo = xmlNewChild(Raiz, NULL, (const xmlChar *)("IDUSUARIOBUSCADO"), NULL);
    AgregarIdUsuarioBuscado(Nodo, this->Comando->getIdUsuarioBuscado());
  }
  if (this->Comando->getNick().size() > 0)
  {
    Nodo = xmlNewChild(Raiz, NULL, (const xmlChar *)("NICK"), NULL);
    AgregarNick(Nodo, this->Comando->getNick());
  }
  if (this->Comando->getNombre().size() > 0)
  {
    Nodo = xmlNewChild(Raiz, NULL, (const xmlChar *)("NOMBRE"), NULL);
    AgregarNombre(Nodo, this->Comando->getNombre());
  }
  if (this->Comando->getPassword().size() > 0)
  {
    Nodo = xmlNewChild(Raiz, NULL, (const xmlChar *)("PASSWORD"), NULL);
    AgregarPassword(Nodo, this->Comando->getPassword());
  }
  if (this->Comando->getListaDeArchivos().getLongitud() > 0)
  {
    Nodo = xmlNewChild(Raiz, NULL, (const xmlChar *)("LISTADEARCHIVOS"), NULL);

    AgregarListaDeArchivos(Nodo);
  }
  if (this->Comando->getListaDePalabras().getLongitud() > 0)
  {
    Nodo = xmlNewChild(Raiz, NULL, (const xmlChar *)("LISTADEPALABRAS"), NULL);

    AgregarListaDePalabras(Nodo);
  }
}

//******************************************************
// Obtengo el string parseado o a parsear
//******************************************************
TString CXMLParserServidor::getStringParseo() const
{
  return this->StringParseo;
}

//******************************************************
// Setea el string a parsear
//******************************************************
void CXMLParserServidor::setStringParseo(TString StringParseo)
{
  this->StringParseo = StringParseo;
}

//******************************************************
// Destuctor de la clase CXMLPParser
//******************************************************
CXMLParserServidor::~CXMLParserServidor()
{
}
</code>

Salu2!!!!!!!!!!

pandemolde

  • Nuevo Miembro
  • *
  • Mensajes: 13
    • Ver Perfil
Re: Capturando Xml En C Cpn La Libxml
« Respuesta #2 en: Lunes 8 de Agosto de 2005, 13:55 »
0
Gracias Infinitas!!. Me ha servido de mucho. Un  abrazo