Java JAXB Unmarshaller convert xml to Java Object
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; public class Main { public void run(String xmlFile, String context) throws JAXBException, FileNotFoundException { JAXBContext jc = JAXBContext.newInstance(context); Unmarshaller u = jc.createUnmarshaller(); //from ww w . ja va 2 s.c om FileInputStream fis = new FileInputStream(xmlFile); Languages languages = (Languages)u.unmarshal(fis); for (Language p: languages.getLanguage()) { System.out.printf("ID: %s\n", p.getId()); System.out.printf("NAME: %s\n", p.getName()); System.out.printf("DIAGNOSIS: %s\n\n", p.getFeature()); } } public static void main(String[] args) { if (args.length != 2 ) { System.out.printf("Usage: java Main <xmlfile> <context>\n"); System.exit(1); } UnmarshalLanguages app = new UnmarshalLanguages(); try { app.run(args[0], args[1]); } catch (JAXBException ex) { ex.printStackTrace(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } } }
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 ww w .j a va 2 s . c om*/ "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"//from w w w. j a va 2 s .c o m }) @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.j a v a2 s. c om*/ public class ObjectFactory { public ObjectFactory() { } public Languages createLanguages() { return new Languages(); } public Language createLanguage() { return new Language(); } }