0

I have an xml file that looks a little like this :

<Model>
    <Class name="">
        <Attribute name="" type =""/>
        <Attribute\>
        <Method name="" returnType=""/>
    </Class>
</Model>

I was wondering how I could then generate a Java/C++ class from the xml. I have tried using xjc (generating a schema using AltovaXmlSpy ) but I get output that creates a class for each Class, Attribute and Mehthod, rather then putting the methods and attributes inside the Class.

Any Help Appreciated.

  • 1
    You can make your own java code, you can use jaxb to read yours xml file and do some transformation code for write files with you of xml to java code, or make some xsd and use the auto generation with xjc – nicearma Jul 17 '14 at 08:44

3 Answers3

0

Use CodeModel to build the class while parsing the XML, and then output it to a file. Guaranteed compilation (and, if it fails, meaningful errors!).

Maven dependency:

       <dependency>
            <groupId>com.sun.codemodel</groupId>
            <artifactId>codemodel</artifactId>
            <version>2.6</version>
       </dependency>

Sample usage:

JCodeModel cm = new JCodeModel();
JDefinedClass clazz = cm._class("my.package.MyClass");
JMethod method = clazz.method(JMod.PUBLIC, typeOfReturn, "nameOfMethod");
JBlock body = method.body();
// ... add fields, methods, set return types, ... 

// write all in-memory classes to file, with import-blocks and everything
cm.build(destinationDirectory);
tucuxi
  • 17,561
  • 2
  • 43
  • 74
0

If you generate an xsd from your xml it is possible to use jaxb or visual studio to generate classes. This is discussed in another question. Read about it here:

Community
  • 1
  • 1
emanciperingsivraren
  • 1,215
  • 2
  • 15
  • 27
0

use this code get the class name and attribute name

NodeList stdCol = doc.getElementsByTagName("Model");

      for(int s=0; s<stdCol.getLength() ; s++){
          Element el = (Element)stdCol.item(s);
          NodeList stdClass  = el.getElementsByTagName("Class ");
          for(int k=0; k<stdClass .getLength() ; k++){
              Element mapEntry = (Element)stdClass .item(k);
              NodeList stdAttribute  = mapEntry.getElementsByTagName("Attribute ");

and so on

suresh manda
  • 659
  • 1
  • 8
  • 25