Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Internet (https://www.clubdelphi.com/foros/forumdisplay.php?f=3)
-   -   Leer XML Sin Grabarlo a Disco (https://www.clubdelphi.com/foros/showthread.php?t=91377)

webmasterplc 20-01-2017 12:16:12

Leer XML Sin Grabarlo a Disco
 
Buenas, ahorita estoy tratando de conectarme al portal web del SENIAT en Venezuela tratando de consultar los rif de los contribuyentes para registrar los datos en la base de datos, la consulta se hace via GET y uso el código siguiente.

Código Delphi [-]
begin
Stream := TMemoryStream.Create;
rif:=edt1.Text;
    try
    idhttp1.Get('http://contribuyente.seniat.gob.ve/getContribuyente/getrif?rif='+rif, Stream);
    Stream.Seek(0, soFromBeginning);
    Stream.SaveToFile('c:\proyectos\consulta\rif.xml');
    except on e: exception do
     begin
       ShowMessage('Error'+e.Message);
     end;

    end;



end;

El Portal me regresa un xml con la siguiente estructura
<?xml version="1.0" encoding="ISO-8859-1"?>
<rif:Rif xmlns:rif="rif" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" rif:numeroRif="V148276192"><rif:Nombre>BERTHGENIS SAMUEL DELGADO</rif:Nombre><rif:AgenteRetencionIVA>NO</rif:AgenteRetencionIVA><rif:ContribuyenteIVA>SI</rif:ContribuyenteIVA><rif:Tasa>100</rif:Tasa></rif:Rif>


este lo guardo en
Código Delphi [-]
Stream: TMemoryStream;
y lo grabo en disco si no hay error
Código Delphi [-]
Stream.SaveToFile('c:\proyectos\consulta\rif.xml');

la pregunta es que posibilidad de leer este xml sin necesidad de guardarlo a disco agradezco su ayuda.
Uso delphi XE8

AgustinOrtu 20-01-2017 16:22:29

No se pueden cargar los XML desde stream? Me imagino que la clase XMLDocument tiene el método LoadFromStream, ya que LoadFromFile por lo general está implementando usando ese método

webmasterplc 20-01-2017 17:12:37

Hay alguna manera de cargarlos a una variable desde internet y no guardarlos a disco?

AgustinOrtu 20-01-2017 17:22:23

Si, usando Streams o directamente asignando strings:

Código Delphi [-]
uses
  System.SysUtils,
  System.Classes,
  Xml.XMLIntf,
  Xml.XMLDoc;

procedure Main;
var
  xml: IXMLDocument;
  Stream: TMemoryStream;
  StringStream: TStringStream;
begin
  // Alternativa #1
  xml := TXMLDocument.Create(nil);
  xml.LoadFromStream(Stream);
  xml.LoadFromStream(Stream, TXMLEncodingType.) // sobrecarga que permite especificar un Encoding

  // Alternativa #2 usando TStringStream
  StringStream := TStringStream.Create;
  // en lugar de descargar a un TMemoryStream descargas a un TStringStream
  idhttp1.Get('blablabla', StringStream);
  xml := LoadXMLDocument(StringStream.DataString);

  // Alternativa #3 tambien con TStringStream
  xml := TXMLDocument.Create(nil);
  xml.XML := StringStream.DataString;
end;

webmasterplc 25-01-2017 02:40:21

bueno he estado intentando por ahora lo leere de disco mientras sigo dando golpes
estoy tratando de pasar el contenido de los nodos a un edit y me sale en blanco
Código Delphi [-]
var
Cliente: IXMLNode;
begin
docxml1.FileName:=( ExtractFilePath( Application.ExeName ) + 'rif.xml' );
  docxml1.Active := True;
  Cliente := docxml1.DocumentElement.ChildNodes[0];
  edt2.Text:= Cliente.ChildNodes['rif:Nombre'].Text ;
end;

este es el xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<rif:Rif xmlns:rif="rif" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" rif:numeroRif="V148276192"><rif:Nombre>BERTHGENIS SAMUEL DELGADO</rif:Nombre><rif:AgenteRetencionIVA>NO</rif:AgenteRetencionIVA><rif:ContribuyenteIVA>SI</rif:ContribuyenteIVA><rif:Tasa>100</rif:Tasa></rif:Rif>

AgustinOrtu 25-01-2017 05:26:35

Como parentesis aparte, cuando se trata de XML, con Delphi lo tenes mucho mas sencillo. Tiene una herramienta integrada llamada XML Data Binding. Basicamente le das un archivo XML (o un esquema que describe la estructura, un archivo XSD) y automaticamente lo lee y te genera interfaces para acceder a las todas las propiedades del XML usando objetos. Tambien te resuelve el problema de los nodos hijos. Yo le pegaria un vistazo: http://docwiki.embarcadero.com/RADSt...Binding_Wizard

AgustinOrtu 25-01-2017 05:34:29

Por ejemplo, usando el XML que pusiste en el post de arriba, me genera esta interface:

Código Delphi [-]
  IXMLRifType = interface(IXMLNode)
    ['{4288BB28-3181-42AD-9F90-288F1CD5B4E5}']
    function GetNumeroRif: string;
    function GetNombre: string;
    function GetAgenteRetencionIVA: string;
    function GetContribuyenteIVA: string;
    function GetTasa: Integer;

    property NumeroRif: string read GetNumeroRif;
    property Nombre: string read GetNombre;
    property AgenteRetencionIVA: string read GetAgenteRetencionIVA;
    property ContribuyenteIVA: string read GetContribuyenteIVA;
    property Tasa: Integer read GetTasa;
  end;

Y tambien una clase que la implementa

Código Delphi [-]
  TXMLRifType = class(TXMLNode, IXMLRifType)
  protected
    function GetNumeroRif: string;
    function GetNombre: string;
    function GetAgenteRetencionIVA: string;
    function GetContribuyenteIVA: string;
    function GetTasa: Integer;
  end;

Luego tambien te da unas funciones globales que sirven para leer o inicializar las interfaces de arriba y poder trabajar con el XML

Código Delphi [-]
  function GetRif(const Doc: IXMLDocument): IXMLRifType;
  function LoadRif(const FileName: string): IXMLRifType;
  function NewRif: IXMLRifType;

Entonces podes escribir este tipo de codigo y te olvidas de tener que andar analizando nodo a nodo para encontrar la informacion:

Código Delphi [-]
var
  Xml: IXMLRifType;
begin
  Xml := LoadRif('RutaArchivo');
  ShowMessage(Xml.AgenteRetencionIVA);
  ShowMessage(Xml.NumeroRif);
end;

webmasterplc 25-01-2017 10:54:35

Gracias Hermano


La franja horaria es GMT +2. Ahora son las 19:21:08.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi