Java JAXB Marshaller convert Object to XML
import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.math.BigInteger; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; public class Main { public static void main(String[] args) { if (args.length != 2) { System.out.println("Usage: Main <xmlfile> <context>"); System.exit(1);// w w w . j a v a2 s . co m } MarshalLanguages app = new MarshalLanguages(); try { app.run(args[0], args[1]); } catch (JAXBException ex) { ex.printStackTrace(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } } public void run(String xmlFile, String context) throws JAXBException, FileNotFoundException { Languages languages = new Languages(); List<Language> languageList = languages.getLanguage(); Language p = new Language(); p.setId(BigInteger.valueOf(1)); p.setName("CSS"); p.setFeature("Tester"); languageList.add(p); JAXBContext jc = JAXBContext.newInstance(context); Marshaller m = jc.createMarshaller(); m.marshal(languages, new FileOutputStream(xmlFile)); } }
Language.java
import java.math.BigInteger; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Language", propOrder = { "name",/*from www . j av a 2 s .co m*/ "feature" }) public class Language { @XmlElement(required = true) protected String name; @XmlElement(required = true) protected String feature; @XmlAttribute(name = "id", required = true) protected BigInteger id; public String getName() { return name; } public void setName(String value) { this.name = value; } public String getFeature() { return feature; } public void setFeature(String value) { this.feature = value; } public BigInteger getId() { return id; } public void setId(BigInteger value) { this.id = value; } }
Languages.java
import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "language"// ww w. j av a 2 s.c om }) @XmlRootElement(name = "languages") public class Languages { @XmlElement(required = true) protected List<Language> language; public List<Language> getLanguage() { if (language == null) { language = new ArrayList<Language>(); } return this.language; } }
ObjectFactory.java
import javax.xml.bind.annotation.XmlRegistry; @XmlRegistry//from w ww .ja v a 2s . c o m public class ObjectFactory { public ObjectFactory() { } public Languages createLanguages() { return new Languages(); } public Language createLanguage() { return new Language(); } }