Question

I want to view the below defined xml schema into my expected xml. Can anyone help me what to write in XSD. Thanks in advance. XML SCHEMA:

<xs:element name="Animal">
                      <xs:complexType>
                        <xs:simpleContent>
                          <xs:extension base="xs:string">
                            <xs:attribute name="type" type="xs:string" />
                          </xs:extension>
                        </xs:simpleContent>
                      </xs:complexType>
                    </xs:element>

EXPECTED OUTPUT in XML: <Animal type="carnivore">Tiger</Animal>.

Was it helpful?

Solution

With a schema containing only the element you showed, you can generate the instance you want in Java using JAXB. I added some context to your example, and included a namespace. This is the full XML Schema file (I called it animals.xsd):

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" 
           xmlns="http://animals"
           targetNamespace="http://animals"
           elementFormDefault="qualified">
    <xs:element name="Animal">
        <xs:complexType>
            <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) you can generate classes from XML Schemas. So you can simply run:

xjc animals.xsd

And it will generate these files

animals/Animal.java
animals/ObjectFactory.java
animals/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 animals.Animal;
import javax.xml.bind.*;

public class App {

    public static void main(String[] args) throws JAXBException {
        Animal tiger = new Animal();
        tiger.setType("carnivore");
        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);
    }
}

The result will be printed to the console:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Animal xmlns="http://animals" type="carnivore">Tiger</Animal>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top