Generate an XSD from Java
On June 7, 2014 by --- With 0 Comments
- Uncategorized
This is not your usual generate code. Instead of generating an XSD based on Java classes, I wanted to generate an XSD from my Java code. The below code requires Apache XML Beans.
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.impl.xb.xsdschema.*;
import java.io.IOException;
import java.math.BigInteger;
public class Test {
public static void main(String[] args) throws IOException, IllegalAccessException, InstantiationException, XmlException {
// Start by parsing in a base schema
SchemaDocument parse = SchemaDocument.Factory.parse(
"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">\n" +
"</xs:schema>\n");
// Add a new element to the schema
TopLevelElement topLevelElement = parse
.getSchema()
.addNewElement();
topLevelElement.setName("YourTopElementName");
LocalElement localElement = topLevelElement
.addNewComplexType()
.addNewSequence()
.addNewElement();
localElement.setName("YourSubElement");
localElement.setMinOccurs(new BigInteger("1")); // make it a required element
localElement.setMaxOccurs(new BigInteger("1")); // make it a 1...1 element
// Write to string and print to screen
String s = parse.xmlText();
System.out.println(s);
}
}
import org.apache.xmlbeans.impl.xb.xsdschema.*;
import java.io.IOException;
import java.math.BigInteger;
public class Test {
public static void main(String[] args) throws IOException, IllegalAccessException, InstantiationException, XmlException {
// Start by parsing in a base schema
SchemaDocument parse = SchemaDocument.Factory.parse(
"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">\n" +
"</xs:schema>\n");
// Add a new element to the schema
TopLevelElement topLevelElement = parse
.getSchema()
.addNewElement();
topLevelElement.setName("YourTopElementName");
LocalElement localElement = topLevelElement
.addNewComplexType()
.addNewSequence()
.addNewElement();
localElement.setName("YourSubElement");
localElement.setMinOccurs(new BigInteger("1")); // make it a required element
localElement.setMaxOccurs(new BigInteger("1")); // make it a 1...1 element
// Write to string and print to screen
String s = parse.xmlText();
System.out.println(s);
}
}
Comments are Disabled