Generate java file from XML file without any API -
how can generate java file, means generate name of classes methods attributes, without using api 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 appreciated
thank you
if still want own. might have on simplified example.
warnings first:
- it lacks proper exception handling
- it build work 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(); } } { if (parser != null) { parser.close(); } } return source; } static void processendelement(xmlstreamreader reader, stringbuilder sb) { string element = reader.getlocalname(); if ("class".equals(element)) { sb.append("}"); } else if ("attribut".equals(element)) { sb.append(";\n"); } } static void processcharacters(xmlstreamreader reader, stringbuilder sb) { if (!reader.iswhitespace()) { sb.append(" ").append(reader.gettext()); } } static void processstartelement(xmlstreamreader reader, stringbuilder sb) { string element = reader.getlocalname(); if ("class".equals(element)) { sb.append("public class ") .append(reader.getattributevalue(0)) .append(" {\n"); } else if ("attribut".equals(element)) { sb.append(" ") .append(reader.getattributevalue(0)); } } }
assuming source.xml
contains
<class name="person"> <attribut type="int">age</attribut> <attribut type="string">name</attribut> </class>
the code prints
public class person { int age; string name; }
the "only" thing left do: implement missing parts. if still contains "too much" xml api ... ... write own parser. ;-)
Comments
Post a Comment