Java HTML / XML How to - Create valid xml using xsd schema








Question

We would like to know how to create valid xml using xsd schema.

Answer

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" 
           xmlns="http://myclass"
           targetNamespace="http://myclass"
           elementFormDefault="qualified">
    <xs:element name="Animal">
        <xs:complexType>/* w ww  .j a v  a2s . c o  m*/
            <xs:simpleContent>
                <xs:extension base="xs:string">
                    <xs:attribute name="type" type="xs:string" />
                </xs:extension>
            </xs:simpleContent>
        </xs:complexType>
    </xs:element>   
</xs:schema>

Using the xjc tool (XSD to Java Compiler) to generate classes from XML Schemas.

So you can simply run:

xjc myclass.xsd

And it will generate these files

myclass/Animal.java
myclass/ObjectFactory.java
myclass/package-info.java

Place these in your classpath.

Now you can write a simple program where you can create instances using that class, and then serialize it to XML using a JAXB marshaller:

import myclass.Animal;
import javax.xml.bind.*;
/*from   ww w  .  j a  va 2  s  . c  om*/
public class Main {

    public static void main(String[] args) throws JAXBException {
        Animal tiger = new Animal();
        tiger.setType("A");
        tiger.setValue("Tiger");

        JAXBContext jaxbContext = JAXBContext.newInstance(Animal.class);
        Marshaller m = jaxbContext.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(tiger, System.out);
    }
}