用命令將 xsd 轉成 javaben 很簡單
1. import java.io.File;
2. import java.io.IOException;
3. import javax.xml.bind.JAXBContext;
4. import javax.xml.bind.JAXBException;
5. import javax.xml.bind.SchemaOutputResolver;
6. import javax.xml.transform.Result;
7. import javax.xml.transform.stream.StreamResult;
8.
9.
10.
11. public CustomSchemaOutputResolver resolver;
12.
13. public static void main(String[] args) {
14. XSDCreate xsdCreate = new XSDCreate();
15. xsdCreate.resolver = xsdCreate.new CustomSchemaOutputResolver("F:\\schema", "student.xsd");
16.
17. Class[] classes = { Student.class };
18. xsdCreate.createXSD(classes);
19.
20. System.out.println("all done");
21. }
22.
23. public void createXSD(Class[] classes) {
24. try {
25. JAXBContext context = JAXBContext.newInstance(classes);
26. context.generateSchema(resolver);
27. } catch (JAXBException e) {
28. e.printStackTrace();
29. } catch (IOException e) {
30. e.printStackTrace();
31. }
32. }
33.
34. public class CustomSchemaOutputResolver extends SchemaOutputResolver {
35.
36. private File file;
37.
38. public CustomSchemaOutputResolver(String dir, String fileName) {
39. try {
40. file = new File(dir, fileName);
41. if (!file.exists()) {
42. file.createNewFile();
43. }
44. } catch (IOException e) {
45. e.printStackTrace();
46. }
47. }
48.
49. @Override
50. public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException {
51. return new StreamResult(file);
52. }
53.
54. }
55. }