Java Reference
In-Depth Information
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 .
Example2-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
Search WWH ::




Custom Search