by

How to marshal and unmarshal java class to xml file using JAX-B

This java code shows how to marshal and unmarshal class data to xml using JAX-B library, contained in javax.xml.bind.JAXB package.
MyNetwork object contains two lists, one for Vendor objects and one for Equipment objects.
Each Equipment has a list of Cards and each card refers to a specific Vendor.
Marshalling and unmarshalling operation is delegate to JAXB framework, writing and reading a xml file containg the class structure.
MyNetwork, Equipment, and Vendor classes explained in the snippet linked below.
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/42432/How-to-marshal-and-unmarshal-java-class-?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
package com.test.jaxb; import java.io.File; import javax.xml.bind.JAXB; public class MarshallingExamples { public MarshallingExamples() { MyNetwork network = new MyNetwork(); Vendor v1 = new Vendor("123", "NameVVV"); Vendor v2 = new Vendor("567", "NameZZZ"); Vendor v3 = new Vendor("345", "NameXXX"); Equipment eqp1 = new Equipment("112233", "TYPE_ABC", "00-14-22-01-23-45"); eqp1.addCard(new Card(CardType.DWDM, "AABBCC", 2, v1)); network.addEquipments(eqp1); Equipment eqp2 = new Equipment("222333", "TYPE_ZZZ", "00-C4-22-C1-23-C5"); eqp2.addCard(new Card(CardType.SDH, "AA1234", 1, v2)); eqp2.addCard(new Card(CardType.ETH, "AACCDD", 4, v1)); network.addEquipments(eqp2); Equipment eqp3 = new Equipment("445566", "TYPE_CDE", "01-C3-2A-C1-AA-C5"); eqp3.addCard(new Card(CardType.DWDM, "AAFF44", 1, v3)); eqp3.addCard(new Card(CardType.DWDM, "AABF33", 1, v3)); eqp3.addCard(new Card(CardType.ETH, "AA33DD", 2, v2)); network.addEquipments(eqp3); network.addVendor(v1); network.addVendor(v2); network.addVendor(v3); JAXB.marshal(network, new File("out.xml")); network = JAXB.unmarshal(new File("out.xml"), MyNetwork.class); for(Equipment eqp : network.getEquipments()) { System.out.println(eqp); } for(Vendor vend : network.getVendors()) { System.out.println(vend); } } public static void main(String[] args) { new MarshallingExamples(); } }

Other Steps and Solutions

If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus