Can anyone please explain the difference between UnMarshaller and Parser in JAXB. I have read like UnMarshaller is used to retrieve the value from XML document. Parser also does the same thing. Anyone please explain the difference.
eg:consider the below example zoo.xml
<zoo>
<zooName>Vandalur Zoo</zooName>
<zooId>12321</zooId>
<animals>
<animal>
<animalName>Lion</animalName>
<animalType>Wild</animalType>
</animal>
Using UnMarshaller,
JAXBContext jaxbContext = JAXBContext
.newInstance("com.javapapers.xml.jaxb");
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
JAXBElement<?> zoo = (JAXBElement<?>) unmarshaller
.unmarshal(new FileInputStream("zoo.xml"));
ZooInfo zooInfo = (ZooInfo) zoo.getValue();
Using parser:
File fXmlFile = new File("zoo.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
Both your examples involve parsing the XML as the first step. They differ in what happens next. The "unmarshaller" turns the output of the parser into Java objects whose class definitions match the structure of the XML. The second example turns the output of the parser into a direct tree representation of the XML.
The term "parser" is much abused in the XML world. It's very often used to describe the application that processes the data once it is parsed, rather than just the parser component itself. In your case you are comparing a (parser plus unmarshaller) with a (parser plus tree builder).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With