Validação de Schema XML de NFe - exemplo C#
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 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 Manual de Integração do Contribuinte - versão 2.02 estão disponíveis no PL_005a.zip são necessários para a execução da aplicação.
ValidaXML.cs (3.1 KB, 10,538 downloads)
NF-e.xml - versão 1.10 (5.7 KB, 54,367 downloads)
NFe_assinada.xml - versão 1.10 (6.3 KB, 20,594 downloads)
NFe_falhaSchema.xml - versão 1.10 (5.7 KB, 16,712 downloads)
ValidaXML.zip (48 KB, 11,793 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(”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 xmlreader.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);
}
}
}
Tags: NF-e, NFE, Nota Fiscal eletronica, PL_003b, PL_005a, Schema XML, validacao Schema XML, WS