View on GitHub

JLibs

Common Utilities for Java

Generate sample XML from XML-Schema

First you parse the schema file using XSParser:

import jlibs.xml.xsd.XSParser;
import org.apache.xerces.xs.*;

XSModel xsModel = new XSParser().parse("purchageOrder.xsd");

Create an instanceof XSInstance and configure various options:

import jlibs.xml.xsd.XSInstance;

XSInstance xsInstance = new XSInstance();
xsInstance.minimumElementsGenerated = 2;
xsInstance.maximumElementsGenerated = 4;
xsInstance.generateOptionalElements = Boolean.TRUE; // null means random

now genreate the sample xml as follows:

import jlibs.xml.sax.XMLDocument;

QName rootElement = new QName("http://jlibs.org", "PurchaseOrder");
XMLDocument sampleXml = new XMLDocument(new StreamResult(System.out), true, 4, null);
xsInstance.generate(xsModel, rootElement, sampleXml);

Configuring Sample Values

let us say the sample generated by XSInstance is as below:

<company>
    <employee>
        <name>name1</name>
        <age>99</age>
    </employee>
    <employee>
        <name>name2</name>
        <age>99</age>
    </employee>
</company>

now you want to specify default value for employee name. create defaults.xml as below:

<company>
    <employee>
        <name>scott</name>
        <name>adam</name>
        <name>eve</name>
    </employee>
</company>

i.e default.xml structure remains compatible with sample xml generated. but contains only those elements for which you wants defaults.

Notice that we specified 3 default values for employee name. i.e you can specify as many default values you need. and they are chosen randomly during sample xml generation.

now plugin defaults.xml into XSInstance as below:

XSModel xsModel = new XSParser().parse("company.xsd");
XSInstance xsInstance = new XSInstance();
XMLDocument xml = new XMLDocument(...);
xsInstance.sampleValueGenerator = new XMLSampleValueGenerator(xsModel, new InputSource("defaults.xml"));
xsInstance.generate(...);

this will generated following sample xml with your defaults:

<company>
    <employee>
        <name>scott</name>
        <age>99</age>
    </employee>
    <employee>
        <name>eve</name>
        <age>99</age>
    </employee>
</company>

Commandline Utility

You can find command line utility xsd-instance.sh in jlibs/bin directory.

xsd-instance.sh <xsd-file> [root-element]

for example:

xsd-instance.sh purchase-order.xsd {http://jlibs.org}PurchaseOrder

here root-element is optional. If not specified:

you can configure various options in jlibs/bin/xsd-instance.properties

minimumElementsGenerated=2
maximumElementsGenerated=4
minimumListItemsGenerated=2
maximumListItemsGenerated=4

# for following properties value can be always/never/random
generateOptionalElements=always
generateOptionalAttributes=always
generateFixedAttributes=always
generateDefaultAttributes=always