有没有人设法从没有XJC的JAXB模式文件生成java代码?
与
有些相似JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler()
用于动态编译java代码。
注意:在JDK 6上运行,意味着不推荐使用com.sun.*
工具包(感谢Blaise Doughan提示)
答案 0 :(得分:5)
我必须为我的解决方案包含一些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
中答案 1 :(得分:3)
此代码以特定的目录/包结构生成文件:
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));
}
}
答案 2 :(得分:1)
答案 3 :(得分:1)
获取JAXB参考实现here。
它包含允许您生成Java代码的com.sun.tools.xjc.api.XJC类。
答案 4 :(得分:0)
在Maven中获取依赖项的另一种方法;
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-xjc</artifactId>
<version>2.2.11</version>
</dependency>