Validação de arquivo xml através de XSD

5 respostas
D

Boa tarde a todos!

Pessoal, estou fazendo o projeto da NFe (Nota Fiscal Eletrônica) e estou com problemas na validação do xml através do xsd disponibilizado pela SEFAZ.

Está dando o erro:

org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element NFe.

at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)

at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(Unknown Source)

at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)

at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)

at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(Unknown Source)

at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(Unknown Source)

at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)

at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(Unknown Source)

at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)

at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(Unknown Source)

at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)

at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(Unknown Source)

at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)

at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)

at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)

at com.sun.org.apache.xerces.internal.jaxp.validation.StreamValidatorHelper.validate(Unknown Source)

at com.sun.org.apache.xerces.internal.jaxp.validation.ValidatorImpl.validate(Unknown Source)

at javax.xml.validation.Validator.validate(Unknown Source)

at teste.Teste2.validaXML2(Teste2.java:120)

at teste.Teste2.main(Teste2.java:37)

o meu código (fiz um código pra testar) é:

try {
		
		xml = new FileInputStream("C:\\Program Files\\jboss-5.1.0.GA-jdk6\\jboss-5.1.0.GA\\mundial\\notas_assinadas\\33090733304981000110550010000003680000003681-nfe.xml");
	    InputStream xsd1 = new FileInputStream("D:\\Projetos\\NFe\\Sefaz\\xsd\\leiauteNFe_v1.10.xsd"); 
	    InputStream xsd2 = new FileInputStream("D:\\Projetos\\NFe\\Sefaz\\xsd\\tiposBasico_v1.02.xsd");
	    InputStream xsd3 = new FileInputStream("D:\\Projetos\\NFe\\Sefaz\\xsd\\xmldsig-core-schema_v1.01.xsd");
	    
	    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
	    
	    StreamSource src1 = new StreamSource(xsd1);
	    StreamSource src2 = new StreamSource(xsd2);
	    StreamSource src3 = new StreamSource(xsd3);
	    Source[] sources = new Source[] {src3, src2, src1};

// Source[] sources = new Source[] {src1, src2, src3};
Schema schema = factory.newSchema(sources);

javax.xml.validation.Validator v = schema.newValidator();
	    
	    v.validate(new StreamSource(xml));

	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (SAXException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}

alguém me ajude por favor!!!.. já estou a dois dias nisso e não consigo sair do lugar.

Se tiverem outras sugestões de como fazer essa validação também será bem vinda!!!

abraços e obrigado.

5 Respostas

J

Boas DrCosta,
Estou com o mesmo problema voce conseguiu resolver esta validação?

J

@drcosta qual era o erro que vc tava tendo ?

Conseguiu resolver ? ?

Segue o probelma que estou tendo com a validação …

public static void main(String args[]) {
		
		TEnvEvento envEvento = gerarEventoConfirmacao();

		try {

			StringWriter writer = new StringWriter();
			JAXBContext context = JAXBContext.newInstance("br.com.gko.entidades.md.evento");
			Marshaller marshaller = context.createMarshaller();
			JAXBElement<TEnvEvento> element = new ObjectFactory().createEnvEvento(envEvento);
			marshaller.marshal(element, writer);

			String xml = writer.getBuffer().toString();
			
			System.out.println(xml);
						
			String leiaute = FileHelper.obterArquivoXsd("leiauteConfRecebto_v1.00.xsd");
			String tiposBasicos = FileHelper.obterArquivoXsd("tiposBasico_v1.03.xsd");
			String xmldsig = FileHelper.obterArquivoXsd("xmldsig-core-schema_v1.01.xsd");
			
			
			SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 
			try {
				
			StreamSource src1 = new StreamSource(new ByteArrayInputStream(leiaute.getBytes("UTF-8")));
			StreamSource src2 = new StreamSource(new ByteArrayInputStream(tiposBasicos.getBytes("UTF-8")));
			StreamSource src3 = new StreamSource(new ByteArrayInputStream(xmldsig.getBytes("UTF-8"))); 
			Source[] sources = new Source[] {src3, src2, src1}; 			
				
				Schema schema = factory.newSchema(sources);
				javax.xml.validation.Validator v = schema.newValidator();
				v.validate(new StreamSource(xml)); 
				
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} 

			
			System.out.println(transformaXMLEmTEnvi(xml));
			

		} catch (JAXBException e) {
			e.printStackTrace();
		}

	}

xml sendo validado :

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
	<ns2:envEvento xmlns:ns2="http://www.portalfiscal.inf.br/nfe" xmlns:ns3="http://www.w3.org/2000/09/xmldsig#">
		<ns2:idLote>000000013199200</ns2:idLote>
		<ns2:evento><ns2:infEvento Id="ID2102003511051014278500019055111000000013199881790001">
			<ns2:cOrgao>RJ</ns2:cOrgao>
			<ns2:tpAmb>2</ns2:tpAmb>
			<ns2:CNPJ>10142785000190</ns2:CNPJ>
			<ns2:chNFe>35110510142785000190551110000000131998817900</ns2:chNFe>
			<ns2:dhEvento>2012-08-24T11:40:25-11:40</ns2:dhEvento>
			<ns2:tpEvento>210200</ns2:tpEvento>
			<ns2:nSeqEvento>1</ns2:nSeqEvento>
			<ns2:verEvento>1.00</ns2:verEvento>
			<ns2:detEvento versao="1.00">
				<ns2:descEvento>Confirmacao da Operacao</ns2:descEvento>
			</ns2:detEvento>
		</ns2:infEvento>
	</ns2:evento>
</ns2:envEvento>

O erro :

Claro que o xml ta sendo enviado tudo em uma linha só por isso lineNumber:99

Por favor alguem ajude !!!

J

Segue a solução que resolveu meu problema ! :wink:

private List<String> validateXml(String xml, String xsd) throws Exception {  
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
        factory.setNamespaceAware(true);  
        factory.setValidating(true);  
        factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");  
        factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", xsd);  
        DocumentBuilder builder = null;  
        try {  
            builder = factory.newDocumentBuilder();  
            builder.setErrorHandler(this);  
        } catch (ParserConfigurationException ex) {  
            error("| validateXml():");  
            throw new Exception(ex.toString());  
        }  
  
        org.w3c.dom.Document document;  
        try {  
            document = builder.parse(new ByteArrayInputStream(xml.getBytes()));  
            org.w3c.dom.Node rootNode  = document.getFirstChild();  
            info("| Validando Node: " + rootNode.getNodeName());  
            return this.getListaComErrosDeValidacao();  
        } catch (Exception ex) {  
            error("| validateXml():");  
            throw new Exception(ex.toString());  
        }  
    }
A

Olá pessoal,

segue a função que uso para validar meu xml da nf-e

public static boolean validaXML(File xml) {

        File f = new File(xml.getAbsolutePath());

        try {
            SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
            File schemaLocation = new File("xsd/nfe_v2.00.xsd");
            Schema schema = factory.newSchema(schemaLocation);
            Validator validator = schema.newValidator();
            Source source = new StreamSource(xml);
            validator.validate(source);
            return true;
        } catch (SAXException ex) {
            JOptionPane.showMessageDialog(null, ex.getLocalizedMessage());
            ex.printStackTrace();
            return false;
        } catch (IOException e) {
            JOptionPane.showConfirmDialog(null, e.getLocalizedMessage());
            e.printStackTrace();
            return false;
        }
    }

espero ter ajudado!

até

R

Pra testes rápidos também tem o link da sefaz do RS que é excelente, valida muito mais do que o formato do XML

https://www.sefaz.rs.gov.br/NFE/NFE-VAL.aspx

Criado 8 de julho de 2009
Ultima resposta 26 de set. de 2012
Respostas 5
Participantes 5