Java Code To Create XML File From XSD

Chapter: XML Last Updated: 23-04-2023 04:57:22 UTC

Program:

            /* ............... START ............... */
                
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class XsdToXml {
    public static void main(String[] args) {
        try {
            // Create a new JAXBContext for the generated classes from the XSD
            JAXBContext context = JAXBContext.newInstance("com.example.generated");

            // Create an Unmarshaller to unmarshal the XSD file
            Unmarshaller unmarshaller = context.createUnmarshaller();

            // Unmarshal the XSD file into a JAXBElement
            JAXBElement<?> element = (JAXBElement<?>) unmarshaller.unmarshal(new File("example.xsd"));

            // Create a Marshaller to marshal the JAXBElement to XML
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            // Marshal the JAXBElement to XML and write to a file
            marshaller.marshal(element, new File("example.xml"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

                /* ............... END ............... */
        

Notes:

  • The Java program converts an XSD (XML Schema Definition) file into an XML file using the javax.xml.bind package in Java.
  • The program starts by creating a new JAXBContext object using the JAXBContext.newInstance method, which takes a package name as an argument. This package name corresponds to the package name of the generated Java classes that were created from the XSD file.
  • Next, the program creates an Unmarshaller object using the createUnmarshaller method of the JAXBContext object, and uses it to unmarshal the XSD file into a JAXBElement object.
  • The program then creates a Marshaller object using the createMarshaller method of the JAXBContext object, and sets the JAXB_FORMATTED_OUTPUT property to true to ensure that the output XML is formatted for readability.
  • Finally, the program marshals the JAXBElement object to an XML file using the marshal method of the Marshaller object, and writes the output to a file.
  • The resulting XML file conforms to the rules defined in the XSD file, and has a structure and contents that depend on the structure and rules defined in the XSD file.

Tags

How to generate XML from XSD using Java #Java Code To Create XML File From XSD #Generate XSD from XML Java

Similar Programs Chapter Last Updated