So based off of the xsd file I created in the aforementioned, here is my xml file representing a train. Cho chooo mother fucker.
<?xml version="1.0" encoding="UTF-8"?> <train xmlns="http://www.noviidesign.com/xjcexample/train" name="Pepper Jack" id="pepper_jack" color="gray"> <car name="Car 1" id="car1" maxPassengers="50" /> <car name="Car 2" id="car2" maxPassengers="75" /> <car name="Car 3" id="car3" maxPassengers="75" /> </train>Pretty simple. If you wanted you could have multiple trains within one file, or multiple files with one train in each and just add some looping to your code. Once again I assume you just have this xml files in your src/main/resources folder.
And here is the code. Not much to it.
InputStream xmlFile = this.getClass().getResourceAsStream("/trains/pepperjack.xml"); JAXBContext jc; try { jc = JAXBContext.newInstance("com.noviidesign.xjcexample"); Unmarshaller u = jc.createUnmarshaller(); JAXBElement<train> root = (JAXBElement<train>) u.unmarshal(xmlFile); Train train = root.getValue(); System.out.println("Train id: " + train.getId()); System.out.println("Train name: " + train.getName()); System.out.println("Train color: " + train.getColor()); for(Car car : train.getCars()){ System.out.println("Car id: " + car.getId()); System.out.println("Car name: " + car.getName()); System.out.println("Car max passangers: " + car.getMaxPassengers()); } } catch (JAXBException ex) { logger.error("Exception in jaxb parsing:", ex); }The only thing to be aware of here is the line where you get the new JAXBContext instance. I pass it the context path (where you'll find the Train and Car classes), but you can also pass it an array of classes, a classloader, or combination of them.
And this is all you'll need in your pom. (you will be using maven...)
<dependencies> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.0</version> </dependency> </dependencies> <plugin>Thats it. Simple like your mom.
No comments:
Post a Comment