Tutorial

Java XML Parser

Published on August 4, 2022
author

Pankaj

Java XML Parser

Java XML parser is used to work with xml data. XML is widely used technology to transport or store data. That’s why there are many java xml parsers available.

Java XML Parser

java xml parser Some of the commonly used java xml parsers are;

  1. DOM Parser
  2. SAX Parser
  3. StAX Parser
  4. JAXB

There are some other APIs also available for XML parsing in java, for example JDOM and JiBX. This java xml parser tutorial is aimed to explore different kinds of XML processing API’s and to learn some common tasks we need to perform with XML such as read, write and edit.

Java XML Parser - DOM

DOM Parser is the easiest java xml parser to learn. DOM parser loads the XML file into memory and we can traverse it node by node to parse the XML. DOM Parser is good for small files but when file size increases it performs slow and consumes more memory.

  1. Read XML File This article shows how to use DOM Parser to parse XML file to Object.
  2. Write XML File This article explains how to use DOM Parser to write Object data to XML file.
  3. Edit XML File DOM Parser can be used to edit XML data also. This article shows how to add elements, remove elements, edit element values, edit attributes in an XML document using DOM Parser.

Java XML Parser - SAX

Java SAX Parser provides API to parse XML documents. SAX Parsers are different than DOM parser because it doesn’t load complete XML into memory and read xml document sequentially. It’s an event based parser and we need to implement our Handler class with callback methods to parse XML file. It’s more efficient than DOM Parser for large XML files in terms of time and memory usage.

  1. Read XML File Learn how to create our Callback Handler class to read XML file to list of Objects using SAX Parser.

StAX Java XML Parser

Java Streaming API for XML (Java StAX) provides implementation for processing XML in java. StAX consists of two sets of API – cursor based API and iterator based API. I have covered this java xml parser extensively in different posts.

  1. Read XML File Using StAX Iterator API In this tutorial we will learn how to read XML iteratively using Java StAX (XMLEventReader).
  2. Write XML File Using StAX Iterator API In this tutorial we will see how we can write XML file in java using StAX Iterator based API (XMLEventWriter).
  3. Read XML File Using StAX Cursor API This article shows how to use StAX Cursor API (XMLStreamReader) to read XML data to Object.
  4. Write XML File Using StAX Cursor API Java StAX Cursor API is very straight forward in creating XML and outputting it. We need to create XMLStreamWriter object and write data into it. This tutorial explains it in detail with example.

Java XML Parser - JDOM

JDOM provides a great Java XML parser API to read, edit and write XML documents easily. JDOM provides wrapper classes to chose your underlying implementation from SAX Parser, DOM Parser, STAX Event Parser and STAX Stream Parser. Benefit of using JDOM is that you can switch from SAX to DOM to STAX Parser easily, you can provide factory methods to let client application chose the implementation.

  1. JDOM Read XML File In this tutorial, we will learn how to read XML file to Object using JDOM XML Parser.
  2. JDOM Write XML File In this tutorial we will learn how to write XML file in Java using JDOM. JDOM Document provides methods to easily create elements and attributes. XMLOutputter class can be used to write the Document to any OutputStream or Writer object.
  3. JDOM Edit XML File JDOM provides very neat way to manipulate XML files, using JDOM is very easy and the code looks clean and readable. In this tutorial we will learn how to add element, remove element, edit element value and edit attribute value.

Java XML Parser - JAXB

Java Architecture for XML Binding (JAXB) provides API for converting Object to XML and XML to Object easily. JAXB was developed as a separate project but it was used widely and finally became part of JDK in Java 6.

  1. JAXB Tutorial Using JAXB is very easy and it uses annotations. We need to annotate Java Object to provide instructions for XML creation and then we have to create Marshaller to convert Object to XML. Unmarshaller is used to convert XML to java Object. In this tutorial we will learn most widely used JAXB annotations and how to convert a Java Object to XML (Marshalling) and XML to Java Object (Unmarhsalling).

Java XML Parser - JiBX

JiBX is a very powerful framework for converting XML data to java object and vice versa. It is very useful in applications integration where XML is the format for data transfer, for example, Web Services and Legacy Systems Integration based on Message Oriented Model (MOM).

  1. JiBX Tutorial There are many frameworks available for XML transformation such as JAXB and XMLBeans but JiBX differs in the approach for XML binding and transformation process. JiBX performs these tasks via utility classes generated at compile time via ant scripts. This approach reduces the processing time by moving away from the traditional two-step process with other parsers to a single step.

XPath

XPath provides syntax to define part of an XML document. XPath Expression is a query language to select part of the XML document based on the query String. Using XPath Expressions, we can find nodes in any xml document satisfying the query string.

  • XPath Tutorial javax.xml.xpath package provides XPath support in Java. To create XPathExpression, XPath API provide factory methods. In this tutorial we will use XPath query language to find out elements satisfying given criteria.

Miscellaneous Java XML parser tasks

  1. Generate Sample XML from XSD in Eclipse If you work on web services, you must have been using XSD’s and to test the webservice, you need to generate XML from XSD file. Eclipse provide a very easy way to generate XML from XSD.
  2. Validate XML against XSD Java XML Validation API can be used to validate XML against an XSD. javax.xml.validation.Validator class is used in this tutorial to validate xml file against xsd file.
  3. Java XML Property File Usually we store configurations parameters for java applications in a property file. In java property file can be a normal property file with key-value pairs or it can be an XML file also. In this example, we will learn how to write property XML file and then read properties from XML property files.
  4. SOAP XML Soap is an Xml based transport protocol. Soap stands for Simple Object Access Protocol. Soap is a lightweight mechanism for exchanging structured and typed information. As it is XML based so it is language and platform independent. In this tutorial you will learn about SOAP XML and how can we create it using Liquid XML Studio software.
  5. Format XML Document A utility class with methods for pretty printing XML and converting XML Document to String and String to XML document.
  6. Convert Document to String and String to Document Sometimes while programming in java, we get String which is actually an XML and to process it, we need to convert it to XML Document (org.w3c.dom.Document). Also for debugging purpose or to send to some other function, we might need to convert Document object to String. Two utility methods to convert String to XML Document and XML Document to String.

I will be adding more java XML parser tutorials here as and when I post more, so don’t forget to bookmark it for future use.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
December 4, 2018

two excel package working.excell; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; //Compare two excel and write to one excel public class CompareArraylistExcel { static Boolean check = false; public static void main(String args[]) throws IOException { try { List excellist1 = new ArrayList(); List excellist2 = new ArrayList(); List excellist3 = new ArrayList(); FileInputStream file1 = new FileInputStream(new File( “al1.xlsx”)); FileInputStream file2 = new FileInputStream(new File( “al2.xlsx”)); // Get the workbook instance for XLS file XSSFWorkbook workbook1 = new XSSFWorkbook(file1); XSSFWorkbook workbook2 = new XSSFWorkbook(file2); // Get first sheet from the workbook XSSFSheet sheet1 = workbook1.getSheetAt(0); XSSFSheet sheet2 = workbook2.getSheetAt(0); // Compare sheets // Get iterator to all the rows in current sheet1 Iterator rowIterator1 = sheet1.iterator(); Iterator rowIterator2 = sheet2.iterator(); Employee emp;//=new Employee(); int j=0; while (rowIterator1.hasNext()) { Row row = rowIterator1.next(); // For each row, iterate through all the columns Iterator cellIterator = row.cellIterator(); emp = new Employee(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); // This is for read only one column from excel for (int ii = 0; ii < 3; ii++) { if (cell.getColumnIndex() == ii) { // Check the cell type and format accordingly switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: System.out.print(cell.getNumericCellValue()); if (ii == 1) emp.setAge(cell.getNumericCellValue()+“”); break; case Cell.CELL_TYPE_STRING: System.out.print(cell.getStringCellValue()); if (ii == 0) emp.setId(cell.getStringCellValue().trim()); if (ii == 2) emp.setName(cell.getStringCellValue()); if (ii == 1) emp.setAge(cell.getStringCellValue()); break; case Cell.CELL_TYPE_BOOLEAN: System.out.print(cell.getBooleanCellValue()); break; } } } } excellist1.add(emp); // System.out.println(“… “); } while (rowIterator2.hasNext()) { Row row = rowIterator2.next(); // For each row, iterate through all the columns Iterator cellIterator = row.cellIterator(); emp = new Employee(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); // This is for read only one column from excel for (int ii = 0; ii < 2; ii++) { if (cell.getColumnIndex() == ii) { // Check the cell type and format accordingly switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: System.out.print(cell.getNumericCellValue()); if (ii == 1) emp.setSalary(cell.getNumericCellValue()+””); break; case Cell.CELL_TYPE_STRING: System.out.print(cell.getStringCellValue()); if (ii == 0) emp.setId(cell.getStringCellValue().trim()); if (ii == 2) emp.setName(cell.getStringCellValue()); if (ii == 1) emp.setSalary(cell.getStringCellValue()); break; case Cell.CELL_TYPE_BOOLEAN: System.out.print(cell.getBooleanCellValue()); break; } } } } excellist2.add(emp); System.out.println(“… “+emp.getSalary()+”…”+emp.getId()); } System.out.println(“book1.xls – " + excellist1.size()); System.out.println(“book1.xls – " + excellist2.size()); writeStudentsListToExcel(excellist1,excellist2,excellist3); // closing the files file1.close(); file2.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } //compare two arraylist and write to one arraylist and write into new file excel private static void writeStudentsListToExcel(List excellist1,List excellist2,List excellist3) { FileOutputStream fos = null; try { fos = new FileOutputStream(“test4.xls”); // ArrayList missingNumbers = new ArrayList(); Employee list3emp; for (int x = 0; x < excellist1.size(); x++) { list3emp=new Employee(); Employee currentUser = (Employee) excellist1.get(x); for (int y = 0; y < excellist2.size(); y++) { Employee list2 = (Employee) excellist2.get(y); // System.out.println(” ids “+ list2.getId()+”…”+currentUser.getId()); if (currentUser.getId().equals(list2.getId())) { System.out.println(“ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd”); list3emp.setId(currentUser.getId()); list3emp.setAge(currentUser.getAge()); list3emp.setName(currentUser.getName()); list3emp.setSalary(list2.getSalary()); System.out.println(" nnnnnnnn “+ list2.getSalary()); break; } } excellist3.add(list3emp); } System.out.println(“final.xls – " + excellist3.size()); for (int i = 0; i < excellist3.size(); i++) { System.out.println(excellist3.get(i).getId()+” “+excellist3.get(i).getSalary()); } XSSFWorkbook workBook = new XSSFWorkbook(); XSSFSheet spreadSheet = workBook.createSheet(“email”); XSSFRow row; XSSFCell cell0; XSSFCell cell1; XSSFCell cell2; XSSFCell cell3; // System.out.println(“array size is :: “+minusArray.size()); int cellnumber = 0; Employee emp; for (int i1 = 0; i1 < excellist3.size(); i1++) { Employee list3 = (Employee) excellist3.get(i1); row = spreadSheet.createRow(i1); cell0 = row.createCell(0); cell1 = row.createCell(1); cell2 = row.createCell(2); cell3 = row.createCell(3); // System.out.print(cell.getCellStyle()); cell0.setCellValue(list3.getName().toString().trim()); cell1.setCellValue(list3.getId().toString().trim()); cell2.setCellValue(list3.getAge()+””); cell3.setCellValue(list3.getSalary()+””); } workBook.write(fos); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // end -write into new file } =============== 4.0.0 poi poi 0.0.1-SNAPSHOT org.apache.poi poi 3.15 org.apache.poi poi-ooxml 3.15 xmlunit xmlunit 1.6 test org.apache.xmlbeans xmlbeans 2.6.0 org.w3c dom 2.3.0-jaxb-1.0.6 org.apache.commons commons-collections4 4.1

- Sekar Karuppan

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    November 22, 2018

    hello Pankaj i need new to store the data what i gat from the xml file in mysql database but without writing any query i think that there is always way to doit if you can help i will be very thinkful.

    - hossam

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      September 8, 2017

      I m learning XML with java Many Thanks for sharing this.

      - Priya

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        May 25, 2017

        Nice Tutorial Is java providing any API to generate XSD programmatically. I having below information using that i want to generate XSD. Root Tag = item | FieldName | FieldType | Xpath | | name | string | “/item” | | quantity | Integer | “/item” | | price | price | “/item” | | amount | Integer | “/item/price” | | currency | string | “/item/price” | My output XSD should look like as below

        - shramik

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          January 23, 2017

          Hi , valuable info sir … I need to read coordinates (x,y) from xml and show it in image form (graph) using java . Can you suggest me how?

          - Rohit

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            November 3, 2014

            I required object type SOAP parsing please provide me small information so i will do that.

            - Sharda Prasad

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              September 9, 2014

              I want to know abt Sax parser . Do you guys have any implementation for Saxb parser . Please upload it. thanks

              - Rajan

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                August 11, 2014

                it’s nice tutorial. actually i want to store all the mouse clicked coordinates in an xml file randomly. how to create the xml file randomly in java with xml?

                - vinayakumar

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  March 9, 2014

                  I want to create xml file randomly and update it. How can I do it. It may helpful if you reply to mail. Thank you sir

                  - Snehasish

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    February 25, 2014

                    how to parse xml with dynamically generated list.

                    - jagadeesh

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Become a contributor for community

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      DigitalOcean Documentation

                      Full documentation for every DigitalOcean product.

                      Resources for startups and SMBs

                      The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                      Get our newsletter

                      Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                      New accounts only. By submitting your email you agree to our Privacy Policy

                      The developer cloud

                      Scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Get started for free

                      Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                      *This promotional offer applies to new accounts only.