O'Reilly logo

Java SOA Cookbook by Eben Hewitt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Validating Against a Schema During Marshaling and Unmarshaling

Problem

You have a Java object object to marshal to XML or an XML document to unmarshal to a Java object. You want to validate that the resulting XML conforms to the specified schema before making the request.

Solution

Use JAXP validation by setting an instance of javax.xml.validation.Schema into the JAXB Marshaler. See Example 2-23.

Example 2-23. Validating an XML instance against a schema during unmarshaling

package com.soacookbook.ch02.jaxb; import java.io.File; import java.io.StringReader; import javax.xml.XMLConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.*; /** * Sets a schema onto the unmarshaller to validate. */ public class ValidateUnmarshal { private static final String SCHEMA = "/home/ehewitt/soacookbook/repository/code/catalog/ws/" + "src/xml/ch02/BookVenetianBlind.xsd"; public static void main(String...arg) { try { //Create context JAXBContext ctx = JAXBContext.newInstance(Book.class); //Create marshaller Unmarshaller um = ctx.createUnmarshaller(); //Create instance of schema SchemaFactory factory = SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI); //Create factory, add options if necessary Schema schema = factory.newSchema( new StreamSource(new File(SCHEMA))); //This sets us up for validation um.setSchema(schema); //Read ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required