Home Ask Login Register

Developers Planet

Your answer is one click away!

Nina PRO February 2016

Generate java file from XML file without any API

How can I generate Java file, means generate name of classes methods attributes, without using any API from XML

my XML file : Source

<class name="person">

<Attribut type="int">Age</Attribut>
<Attribut type="String">Name</Attribut>

to java file:

 public class person {
    int age;
    String Name;

Your help is very appreciated

Thank you


SarthAk February 2016

You can generate java classes from xsd or xml file without using any java code or class file use jaxb https://jaxb.java.net/ or a exe file default provided by java located in jdk bin folder xjc.exe

documentation at https://docs.oracle.com/javase/8/docs/technotes/tools/unix/xjc.html

SubOptimal February 2016

If you still want to do it your own. You might have a look on this simplified example.

Warnings first:

  • it lacks proper Exception handling
  • it is build only to work with your proposed XML example

The sample code

import java.io.FileInputStream;
import java.io.IOException;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

public class XMLStreamReaderDemo {

    public static void main(String[] args) throws Exception {
        String xmlFileName = "source.xml";
        StringBuilder javaSource = transform(xmlFileName);

    static StringBuilder transform(String xmlFileName) throws
            FactoryConfigurationError, IOException, XMLStreamException {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader parser = null;
        StringBuilder source = new StringBuilder();
        try (FileInputStream inputStream = new FileInputStream(xmlFileName)) {
            parser = factory.createXMLStreamReader(inputStream);
            while (parser.hasNext()) {
                switch (parser.getEventType()) {
                    case XMLStreamConstants.START_ELEMENT:
                        processStartElement(parser, source);
                    case XMLStreamConstants.CHARACTERS:
                        processCharacters(parser, source);

                    case XMLStreamConstants.END_ELEMENT:
                        processEndElement(parser, source);
        } finally {
            if (parser != null) {

Post Status

Asked in February 2016
Viewed 2,774 times
Voted 7
Answered 2 times


Leave an answer

Quote of the day: live life