- NF-eletrônica nacional - http://nf-eletronica.com/blog -

Validação de Schema XML de NFe - exemplo C#

Posted By admin On 29-04-2008 @ 2:32 In Schema XML, Tecnologia | Comments Disabled

Todas as mensagens do projeto da NF-e são documentos XML e devem ser previamente validados pela aplicação cliente.

A validação de um documento XML é realizada com a aplicação do respectivo Schema XML, que contêm a definição dos campos e conteúdos válidos para o documento XML.

O código exemplo,  escrito em C#,  ambiente . NET,  realiza a validação de um arquivo XML e pode ser testada com o [1] Microsoft Visual C# 2005 Express Edition (uso gratuito). 

Vale destacar que a aplicação indica todos os erros de Schema XML existentes no arquivo XML.

Os Schemas XML da NF-e compatíveis com o [2] Manual de Integração do Contribuinte - versão 2.02 estão disponíveis no [3] PL_005a.zip são necessários para a execução da aplicação.

Download: ValidaXML.cs  [4] ValidaXML.cs (3.1 KB, 10,205 downloads)

Download: NF-e.xml - versão 1.10  [5] NF-e.xml - versão 1.10 (5.7 KB, 53,812 downloads)

Download: NFe_assinada.xml - versão 1.10  [6] NFe_assinada.xml - versão 1.10 (6.3 KB, 20,127 downloads)

Download: NFe_falhaSchema.xml - versão 1.10  [7] NFe_falhaSchema.xml - versão 1.10 (5.7 KB, 16,326 downloads)

Download: ValidaXML.zip  [8] ValidaXML.zip (48 KB, 11,492 downloads)

using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Windows.Forms;
namespace ValidaXML

{
    class Program
    {       static void Main(string[] args)
        {
            Console.WriteLine(”Exemplo de validação de Schema XML de NF-e\r\r”);
            Console.WriteLine(”Nome do arquivo XML:”);
            string _arquivo = Console.ReadLine();
            if (_arquivo == null)
            {
                Console.WriteLine(”\rNome de arquivo não informado…”);
                Console.ReadLine();
            }
            else if (!File.Exists(_arquivo))
            {
                Console.WriteLine(”\rArquivo {0} inexistente…”, _arquivo);
                Console.ReadLine();
            }
            else
            {
                Console.WriteLine(”Nome do arquivo Schema XML:”);
                string _schema = Console.ReadLine();
                if (_schema == null)
                {
                    Console.WriteLine(”\rNome de arquivo não informado…”);
                    Console.ReadLine();
                }
                else if (!File.Exists(_schema))
                {
                    Console.WriteLine(”\rArquivo de Schema XML {0} inexistente…”, _schema);
                    Console.ReadLine();
                }
                else
                {
                    validaXML(_arquivo, _schema);
                }
        }        private static void validaXML(string _arquivo, string _schema)
        {
        // Create a new validating reader
            XmlValidatingReader reader = new XmlValidatingReader(new XmlTextReader(new StreamReader(System.IO.Path.GetDirectoryName(Application.ExecutablePath).ToString() +”\\”+ _arquivo)));
        // Create a schema collection, add the xsd to it
            XmlSchemaCollection schemaCollection = new XmlSchemaCollection();
           schemaCollection.Add(”[9] http://www.portalfiscal.inf.br/nfe“, System.IO.Path.GetDirectoryName(Application.ExecutablePath).ToString() +”\\”+ _schema);

            // Add the schema collection to the XmlValidatingReader

            reader.Schemas.Add(schemaCollection);

            Console.Write(”Início da validação…\n”);

            // Wire up the call back.  The ValidationEvent is fired when the
            // XmlValidatingReader hits an issue validating a section of the xml

            reader.ValidationEventHandler += new ValidationEventHandler(reader_ValidationEventHandler);

            // Iterate through the xml document

            while (reader.Read()) {}

            Console.WriteLine(”\rFim de validação\n”);
            Console.ReadLine();
        }
      Â
        private static void reader_ValidationEventHandler(object sender, ValidationEventArgs e)
        {

            // Report back error information to the console…
            Console.WriteLine(”\rLinha:{0} Coluna:{1} Erro:{2}\r”, e.Exception.LinePosition, e.Exception.LineNumber, e.Exception.Message);
        }
    }
}


Article printed from NF-eletrônica nacional: http://nf-eletronica.com/blog

URL to article: http://nf-eletronica.com/blog/?p=49

URLs in this post:
[1] Microsoft Visual C# 2005 Express Edition: http://msdn.microsoft.com/en-us/express/aa975050.aspx
[2] Manual de Integração do Contribuinte - versão 2.02: http://nf-eletronica.com/blog/?cat=89
[3] PL_005a.zip: http://www.nfe.fazenda.gov.br/portal/docs/PL_005a.zip
[4] ValidaXML.cs: http://nf-eletronica.com/blog?dl_id=2
[5] NF-e.xml - versão 1.10: http://nf-eletronica.com/blog?dl_id=8
[6] NFe_assinada.xml - versão 1.10: http://nf-eletronica.com/blog?dl_id=9
[7] NFe_falhaSchema.xml - versão 1.10: http://nf-eletronica.com/blog?dl_id=10
[8] ValidaXML.zip: http://nf-eletronica.com/blog?dl_id=6
[9] http://www.portalfiscal.inf.br/nfe: http://www.portalfiscal.inf.br/nfe

Copyright © 2008-2011 NF-eletrônica nacional. All rights reserved.