0

I need to generate XML file based on XSD template in Java, I can parse the XSD file, but don’t know after parsing, hot to generate XML file. Do you know any example or suggestion how to do it please? I’m not very expert on this, so I appreciate any help.

Many thanks in advance.

Arsench
  • 179
  • 2
  • 4
  • 17

1 Answers1

6

Maybe you could use JAXB.

xjc

With xjc, you can convert your XSD file into JAXB annotated Java classes.

xjc -d src -p com.example.jaxb.beans schema.xsd

This would take the types defined in schema.xsd, and generate in the src folder the corresponding classes in the com.example.jaxb.beans package.

JAXBContext & Marshaller

With the generated classes, JAXBContext and Marshaller you can generate some XML output.

JAXBContext jc = JAXBContext.newInstance("com.example.jaxb.beans");
Marshaller m = jc.createMarshaller();
OutputStream os = new FileOutputStream("output.xml");
m.marshal(element, os);

element being an instance of one of the classes generated previously.

superbob
  • 1,628
  • 13
  • 24
  • Many thanks, Ive resolved my problem. The difference with your example was, that I dont have XmlRootElement generated, so I done with diff way, by the way your example helps me to understand the process. Many thanks – Arsench Apr 29 '15 at 14:21
  • Oh, XmlRootElement can be complicated to handle using xjc, [this question](http://stackoverflow.com/questions/819720/no-xmlrootelement-generated-by-jaxb) and [this article](https://weblogs.java.net/blog/2006/03/03/why-does-jaxb-put-xmlrootelement-sometimes-not-always) explains how and why it is generated or not. – superbob Apr 29 '15 at 15:19
  • Thanks for accepting my answer, but if you have a better solution feel free to share it with us : post an answer to your own question. You can even accept it if you consider it to better than my own. – superbob Apr 29 '15 at 15:21