Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between UnMarshaller and Parser in JAXB

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);
like image 422
pandeis Avatar asked Feb 16 '23 20:02

pandeis


1 Answers

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).

like image 83
Michael Kay Avatar answered Mar 04 '23 04:03

Michael Kay