有人成功地在没有使用XJC的情况下从JAXB模式文件生成Java代码吗?
与此类似的:
JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler()
用于动态编译Java代码。
注意:在JDK 6上运行,意味着com.sun.*
工具包已被弃用。(感谢Blaise Doughan的提示)
有人成功地在没有使用XJC的情况下从JAXB模式文件生成Java代码吗?
与此类似的:
JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler()
用于动态编译Java代码。
注意:在JDK 6上运行,意味着com.sun.*
工具包已被弃用。(感谢Blaise Doughan的提示)
我必须导入一些J2EE库才能让我的解决方案工作,因为独立的JDK 6无法访问xjc实用程序类:
import com.sun.codemodel.*;
import com.sun.tools.xjc.api.*;
import org.xml.sax.InputSource;
// Configure sources & output
String schemaPath = "path/to/schema.xsd";
String outputDirectory = "schema/output/source/";
// Setup schema compiler
SchemaCompiler sc = XJC.createSchemaCompiler();
sc.forcePackageName("com.xyz.schema.generated");
// Setup SAX InputSource
File schemaFile = new File(schemaPath);
InputSource is = new InputSource(new FileInputStream(schemaFile));
is.setSystemId(schemaFile.getAbsolutePath());
// Parse & build
sc.parseSchema(is);
S2JJAXBModel model = sc.bind();
JCodeModel jCodeModel = model.generateCode(null, null);
jCodeModel.build(new File(outputDirectory));
*.java源代码将被放置在outputDirectory目录中。
这段代码会在特定的目录/包结构下生成文件:
import java.io.File;
import java.io.IOException;
import org.xml.sax.InputSource;
import com.sun.codemodel.JCodeModel;
import com.sun.tools.xjc.api.S2JJAXBModel;
import com.sun.tools.xjc.api.SchemaCompiler;
import com.sun.tools.xjc.api.XJC;
public class JAXCodeGen {
public static void main(String[] args) throws IOException {
String outputDirectory = "E:/HEAD/JAXB/src/";
// Setup schema compiler
SchemaCompiler sc = XJC.createSchemaCompiler();
sc.forcePackageName("com.xyz.schema");
// Setup SAX InputSource
File schemaFile = new File("Item.xsd");
InputSource is = new InputSource(schemaFile.toURI().toString());
// is.setSystemId(schemaFile.getAbsolutePath());
// Parse & build
sc.parseSchema(is);
S2JJAXBModel model = sc.bind();
JCodeModel jCodeModel = model.generateCode(null, null);
jCodeModel.build(new File(outputDirectory));
}
}
以下内容可能有所帮助:
Maven获取依赖的另一种方式:
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-xjc</artifactId>
<version>2.2.11</version>
</dependency>
java.lang.IllegalArgumentException: system ID 'C:\Users\Federico\Documents\NetBeansProjects\Wadl2Java\myxsd.xsd' isn't absolute
。请问你能帮忙吗? - Federico Bellucciis.setSystemId(schemaFile.toURI().toString())
。 - Federico Bellucci