How to read XML file in Java Using DOM Parser

In this article, we will learn how to read XML file in java using DOM Parser.

DOM stands for Document Object Model.

DOM parser parses the entire XML file, loads it into memory and then models it into a tree structure with each element representing tree branches.

Note:- DOM Parser is slow when XML document contains lot of data because it loads entire file into memory. Consider using SAX Parser when file size is high.

Note :- In Programs, consider changing xmlFile with your system’s file path.

1. Java Program of DOM XML Parser

In this example we will get the node by “name” and display the value.

Output

Root element name :- contactbook Current element name :- employee ————————————- Employee id :- 101 Employee Name : Devil Donald Email: donald.devil@abcd.com Phone: +91 9090909090 Current element name :- employee ————————————- Employee id :- 201 Employee Name : Nevil Ray Email: ray.nevil@abcd.com Phone: +1 919191919

2. Java Program of DOM Parser with looping the nodes.

In this example we will loop through the nodes one by one and will display node name,values and attributes.

Output

Root element name :- contactbook Node Name =contactbook STARTS Node Value = Devil Donald donald.devil@abcd.com +91 9090909090 Nevil Ray ray.nevil@abcd.com +1 919191919 Node Name =employee STARTS Node Value = Devil Donald donald.devil@abcd.com +91 9090909090 Attribute Name : id Attribute Value : 101 Node Name =name STARTS Node Value =Devil Donald Node Name :- name ENDS Node Name =email STARTS Node Value =donald.devil@abcd.com Node Name :- email ENDS Node Name =phone STARTS Node Value =+91 9090909090 Node Name :- phone ENDS Node Name :- employee ENDS Node Name =employee STARTS Node Value = Nevil Ray ray.nevil@abcd.com +1 919191919 Attribute Name : id Attribute Value : 201 Node Name =name STARTS Node Value =Nevil Ray Node Name :- name ENDS Node Name =email STARTS Node Value =ray.nevil@abcd.com Node Name :- email ENDS Node Name =phone STARTS Node Value =+1 919191919 Node Name :- phone ENDS Node Name :- employee ENDS Node Name :- contactbook ENDS

Reference :- Reading XML

It's good to share...Share on FacebookTweet about this on TwitterShare on LinkedInPin on PinterestShare on Google+Email this to someone

Leave a Reply

Your email address will not be published. Required fields are marked *