Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Java to generate xml from an XSD schema

Tags:

java

xml

xsd

I have a requirement to create a sort of 'skeleton' xml based on an XSD schema.

The documents defined by these schemas have no namespace. They are authored by other developers, not in an automated way.

There is no mixed content allowed. That is, elements can contain elements only, or text only.

The rules for this sample xml are:

  • elements that can contain only text content should not be created in the sample xml
  • all other optional and mandatory elements should be included in the sample xml
  • elements should be created only once even if they can occur multiple times
  • any other nodes such as attributes, comments, processing instruction, etc. should be ommited - the sample xml would be an 'element tree'

Are there APIs or tools in Java that can generate such sample xml? I'm looking for pointers where to get started.

This needs to be done programmatically in a reliable way, as the sample xml is used by other XSLT transformations.

like image 294
yas Avatar asked Feb 19 '26 20:02

yas


1 Answers

Hope below code will serve your purpose

    package com.example.demo;
    import java.io.File;

    import javax.xml.namespace.QName;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.TransformerConfigurationException;
    import javax.xml.transform.stream.StreamResult;

    import org.w3c.dom.Document;
    import org.w3c.dom.Element;

    import jlibs.xml.sax.XMLDocument;
    import jlibs.xml.xsd.XSInstance;
    import jlibs.xml.xsd.XSParser;

    public interface xsdtoxml {
         public static void main(String[] pArgs) {
                try {
                    String filename = "out.xsd";
                    // instance.

                    final Document doc = loadXsdDocument(filename);

                    //Find the docs root element and use it to find the targetNamespace
                    final Element rootElem = doc.getDocumentElement();
                    String targetNamespace = null;
                    if (rootElem != null && rootElem.getNodeName().equals("xs:schema")) 
                               {
                        targetNamespace = rootElem.getAttribute("targetNamespace");
                    }


                    //Parse the file into an XSModel object
                    org.apache.xerces.xs.XSModel xsModel = new XSParser().parse(filename);

                    //Define defaults for the XML generation
                    XSInstance instance = new XSInstance();
                    instance.minimumElementsGenerated = 1;
                    instance.maximumElementsGenerated = 1;
                    instance.generateDefaultAttributes = true;
                    instance.generateOptionalAttributes = true;
                    instance.maximumRecursionDepth = 0;
                    instance.generateAllChoices = true;
                    instance.showContentModel = true;
                    instance.generateOptionalElements = true;

                    //Build the sample xml doc
                    //Replace first param to XMLDoc with a file input stream to write to file
                    QName rootElement = new QName(targetNamespace, "out");
                    XMLDocument sampleXml = new XMLDocument(new StreamResult(System.out), true, 4, null);
                    instance.generate(xsModel, rootElement, sampleXml);
                } catch (TransformerConfigurationException e) 
                        {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            public static Document loadXsdDocument(String inputName) {
                final String filename = inputName;

                final DocumentBuilderFactory factory = DocumentBuilderFactory
                        .newInstance();
                factory.setValidating(false);
                factory.setIgnoringElementContentWhitespace(true);
                factory.setIgnoringComments(true);
                Document doc = null;

                try {
                    final DocumentBuilder builder = factory.newDocumentBuilder();
                    final File inputFile = new File(filename);
                    doc = builder.parse(inputFile);
                } catch (final Exception e) {
                    e.printStackTrace();
                    // throw new ContentLoadException(msg);
                }

                return doc;
            }

    }
like image 74
Anuj Kumar Avatar answered Feb 22 '26 17:02

Anuj Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!