Automatic JaxB parsing from XML classes in Java

I am new to jaxb. My question is this: with jaxb, is it possible to automatically map from an XML file to a java object? Starting from an xml file, is there anything generating a Java class with jaxb relaitve annotations?

+4
source share
2 answers

It is really possible. However, you will need an XSD, not an XML file. There are tools ( Trang , for example) that can output XSD from one or more sample XML files.

Please note that creating this XSD with the tool may produce inaccurate results if the XML sample is not completed or if the schema cannot be fully represented in a single XML file (exclusive elements, etc.).

Once you have XSD, use xjc to create the marshaller / non-marshaller classes.

 xjc myxsd.xsd 

This will create annotated classes that JAXB will use for marshalling / unmarshalling. Note that you could also code these classes yourself. After using them, just use them in your code:

 File file = new File("myFile.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(MyRootElement.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); MyRootElement element = (MyRootElement) jaxbUnmarshaller.unmarshal(file); 
+5
source

Yes, JAXB automatically performs marshalling and unmarshalling , but this requires a schema file. JaxB is used to bind XML to Java objects. Using the XSD schema file, it sorts and undoes the token. There are some simple ant tasks, such as XJC, that you can use.

0
source

Source: https://habr.com/ru/post/1479335/


All Articles