How to validate XML with XSD in Java

After initializing xsd with JAXB Binding on Netbeans, you can use a method like this.
Both JAXB binding and schema are same but as far as i see, JAXB unmarshalling doesn’t validate XML, it just transforms it.


package unmarshallertest;

import java.io.*;
import javax.xml.bind.*;
import javax.xml.validation.*;
import oasis.names.specification.ubl.schema.xsd.invoice_2.*;

public class Main {
    public static void main(String[] args) {
        String result;
        InvoiceType inv = new InvoiceType();
        try {
            javax.xml.bind.JAXBContext jaxbCtx = javax.xml.bind.JAXBContext.newInstance("oasis.names.specification.ubl.schema.xsd.invoice_2");
            javax.xml.bind.Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();

            SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = sf.newSchema(new File("C:\\Users\\Kaan\\Desktop\\BELGELER\\UBL-TR files\\UBLTR\\UBL-TR\\xsd\\maindoc\\UBLTR-Invoice-2.0.xsd"));

            unmarshaller.setSchema(schema);

            JAXBElement element=(JAXBElement) unmarshaller.unmarshal(new FileInputStream("fatura.xml")); //NOI18N
            inv=(InvoiceType) element.getValue();
        } catch (Exception ex) {
            // XXXTODO Handle exception
            ex.printStackTrace();
        }
        System.out.println("Validation complete");

    }
}

for oasis.names.specification.ubl.schema.xsd.invoice_2.InvoiceType code is as seen
you can fill it for your own xml and package

Netbeans jaxbu(tab) shortcode doesnt work as intended (At least not now)

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>