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>
</class>

to java file:

 public class person {
    int age;
    String Name;
 }

Your help is very appreciated

Thank you

Answers


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);
        System.out.println(javaSource);
    }

    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);
                        break;
                    case XMLStreamConstants.CHARACTERS:
                        processCharacters(parser, source);
                        break;

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

Post Status

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

Search




Leave an answer