Java XML Tutorial

java xml tutorials

In Java JDK, two built-in XML parsers are available – DOM and SAX, both have their pros and cons. Here’s few examples to show how to create, modify and read a XML file with Java DOM, SAX, JDOM.

In addition, updated JAXB example to show you how to convert object to / from XML.

DOM XML Parser

The DOM is the easiest to use Java XML Parser. It parses an entire XML document and load it into memory, modeling it with Object for easy nodel traversal. DOM Parser is slow and consume a lot memory if it load a XML document which contains a lot of data.

SAX XML Parser

SAX parser is work differently with DOM parser, it does not load any XML document into memory and create some object representation of the XML document. Instead, the SAX parser use callback function (org.xml.sax.helpers.DefaultHandler) to informs clients of the XML document structure.

SAX Parser is faster and uses less memory than DOM parser.

JDOM XML Parser

JDOM provides a way to represent that document for easy and efficient reading, manipulation, and writing. It’s an alternative to DOM and SAX.

JAXB Example

JAXB, using annotation to convert Java object to / from XML file.

  • JAXB 2.0 hello world example
    A detail example to show you use JAXB to do XML Marshalling (convert object to XML) and XML Unmarshalling (Convert XML to object).

XML & Properties

The java.util.Properties class has build-in functionality to convert properties file into XML file or vice versse.

References

  1. Wiki Java_API_for_XML_Processing
  2. DOM XML parser documentation
  3. JDOM XML parser
  4. SAX useful quick start example
  5. SAX XML parser documentation
  6. JAXB Official Website
  7. Properties documentation
  8. Processing XML with Java
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Pingback: stop parking()

  • Pingback: laane penge()

  • Pingback: stop parking()

  • Pingback: fue()

  • Pingback: lan penge her og nu()

  • Pingback: watch free movies online()

  • Pingback: weight loss techniques()

  • Pingback: Blue Coaster33()

  • vara prasad

    I need to know about how to create a xml file which contains parameters of a table and loads it into a database table.?
    please give me some suggestions and will you send the reply to my mail.?

    in advance Thanks to you.

  • Pingback: Quora()

  • Gonzalo Abollado

    Hello,
    Thanks for all the tutorials.
    Very helpful.
    I use your examples a lot.

    Gonzalo.

  • http://android.programmerguru.com/ Android Guru

    You can start learning Android programming from scratch through this blog – http://android.programmerguru.com.
    Blog is targetted for Freshers or novice programmers who want to begin learning Android application development.

  • XYZ

    ur site helps a lot

  • Nirmal
  • Saurabh Kapoor

    Hi!

    I am coding to fetch up RSS feeds and display their contents as per user request. For fetching up RSS feeds, I am using SAX Parser to get only required tag values. But problem starts appearing with values containing special characters like ‘&’ etc. SAX Parser fetches up value only up to the point where & is present.
    Can you provide a solution so that complete set of tag values can be retrieved using SAX Parser? Reason to implement this and not DOM is that XML file coming is quite large one.

  • Zhang Haihai

    Hi,

    I want to select some info in xml, the info position in xml may be changeable. For example, it can be a value of an attribute, but we dont know the attribute name(It will be setted in the configuration file). So, can you suggest me a best choice above to do that.

    Thanks a lot.

  • amit

    How do we implement code for validation in java ???

  • http://www.vehiclesafetyfirm.com Collin

    Very Helpful Tutorials!

  • ganeshkumar.t

    HI MKY,
    I want to transfer a very huge XML data from offline to online in a frequent manner.
    Since the since is very huge , the data transfer is taking time.
    Is thr any brain thoughts from your end to adopt to safer and tricky transfer ?
    Advice pls on any algorithm or !!!! to shrink the data from offline and deflat in Online.

    REgards
    Ganesh K Thiagarajan

  • http://www.lirmm.fr/~seriai/encadrements/theses/rafat/ rafat

    Hi brother
    please help me i want to compare between xml files to extract the common tags and variably between this files please help me

  • Andy

    Hey mykong,

    thx alot for your examples, they are written verry nice and, as result, verry easy to learn from and to get some own ideas of.

    Greetings, Andy

  • art

    Hi mkyong,

    I am your fan. I am learning java from you. Your tutorials are very easy explained .
    Do you know how can I read an XML file and store its data into a database and from the database write an XML file
    I’m driving crazy because I’m lost.

    Cheers

    • http://www.mkyong.com mkyong

      Use JDBC to read/from database, and XML parser for XML data. What’s your problem?

      • art

        Hi Sir,

        Thanks for your reply.

        The problem is i want to read an XML file and store the data from the XML file into a database i.e mysql or oracle and i do not know how to do it.

        Do you have any samples of that?

        Thanks a lot again and sorry for asking such a question.

        • http://www.mkyong.com mkyong

          Learn XML parsers like DOM or SAX to read the data from XML file.

          Learn JDBC to write data into database.

          • art

            Thanks a lot. I’ve done it. I used dom . I reckon dom
            s more flexible if you are using an specific and a complex XML file
            format

  • bradyliu

    I like it

  • http://[email protected] Rupesh Patil

    Hello sir

    I need help

    sir i want java code that read xml file where tag name of xml file is unknown.

    thanks

  • Pingback: Read a XML file with Java()

  • Ramulu

    how to display all the missing tags and exceptions while validating a xml against xsd

  • http://none Yajairo87

    When do we should DOM XML Parser and when do we should use SAX XML Parser? What do we need to evaluate in order to choose one?

    Thanks in advice

    • fucking foreigners

      How about you learn fucking English before you bother to start programming? It’ll help you a lot when it comes to actually making something worth while.

      • Yajairo87

        How about you stop you FUCKING the people who are ‘foreigners’? Came on this is not an apartheid, this is a forum for the issue.

        I’ve been programming since 2005 so please do not talk (or wirte in this case) if you don’t know anything.

        Saludos desde la ciudad de México, from the capital city with love :)

        • Tomas

          Some people are trying their whole life, sometimes to do both.

  • Darshan

    I am facing problem in parsing the XML using DOM on Android application.

    I have data like “A & B” in XML tag. While parsing the XML, it only returns the “A” and ignoring everything after &. How to deal with this problem?

    • ramarajan

      try using DOM Parser and set type=”all” in the

  • mkyong reader

    How can we convert any xml to Java object? looking for generalized solution?

    • Satish

      Using XMLBeans and JAXB.

      • Satish

        That JAXB can be used for static xml.

        We need to write our own parser Stax(XML Streaming parser) inorder to get the complex types first.

        Then pass the complex types one by one (for loop) to Stax parser again inorder to strike out simplexTypes.

        Then we can make use of jdom parser , which will give the XML segment for specific complex type.

        Then we can easily construct the java Object out of that segment.

  • abdur

    i want to modify the second record stored in the xml file but when i try to do this it also goes with the first record.obviously it have some solution please help me to find out the solution. my code is given bellow.

    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.net.URL;
    import org.jdom.Document;
    import org.jdom.Element;
    import org.jdom.JDOMException;
    import org.jdom.input.SAXBuilder;
    //import org.jdom.output.Format;
    import org.jdom.output.XMLOutputter;
     
    public class ModifyXMLFile {
    	public static void main(String[] args) {
     
    	  try {
     
    		SAXBuilder builder = new SAXBuilder();
                    URL FileUrl = null;
                    FileUrl = WriteXMLFile.class.getResource("../crypto");
                    String s=FileUrl.getPath();
                    System.out.println(s.substring(1));
    		File xmlFile = new File(s+"/file.xml");
     
    		Document doc = (Document) builder.build(xmlFile);
    		Element rootNode = doc.getRootElement();
     
    		// update staff id attribute
    		Element staff = rootNode.getChild("staff");
                    Element sta = rootNode.getChild("staff");
     
    		staff.getAttribute("id").setValue("3");
                    /*if(staff.getAttribute("id").getValue().equals("3")){
                      staff.getAttribute("id").setValue("5");
     
                    }*/
                    if(sta.getAttribute("id").getValue().equals("2")){
                      sta.getAttribute("id").setValue("5");
     
                    }
     
     
    		// add new age element
    		Element age = new Element("age").setText("32");
    		staff.addContent(age);
     
    		// update salary value
    		staff.getChild("salary").setText("11000");
     
    		// remove firstname element
    		staff.removeChild("firstname");
     
    		XMLOutputter xmlOutput = new XMLOutputter();
     
    		// display nice nice
    		//xmlOutput.setFormat(Format.getPrettyFormat());
    		xmlOutput.output(doc, new FileWriter(s+"/file.xml"));
     
    		// xmlOutput.output(doc, System.out);
     
    		System.out.println("File updated!");
    	  } catch (IOException io) {
    		System.out.println(io.getCause());//io.printStackTrace();
    	  } catch (JDOMException e) {
    		System.out.println(e.getCause());//e.printStackTrace();
    	  }
    	}
    }
    <?xml version="1.0" encoding="UTF-8"?>
    <company>
        <staff id="3">
            <lastname>mook kim</lastname>
            <nickname>mkyong</nickname>
            <salary>11000</salary>
            <age>32</age>
        <age>32</age></staff>
        <staff id="2">
            <firstname>low</firstname>
            <lastname>yin fong</lastname>
            <nickname>fong fong</nickname>
            <salary>188888</salary>
        </staff>
    </company>
    • Shridharan

      Hi Abdur,

      Please go with the below code. This might help you i guess:

      SAXBuilder builder = new SAXBuilder();
      File xmlFile = new File(“D://Notes/DOMfile.xml”);

      Document doc = (Document) builder.build(xmlFile);
      Element rootNode = doc.getRootElement();

      List childlist = rootNode.getChildren();
      int num = childlist.size();
      for (int i = 0; i < num; i++) {
      Element staff = childlist.get(i);

      Attribute attr = staff.getAttribute("id");
      attr.setValue("5");

      Element age = new Element("age").setText("28");
      staff.addContent(age);

      if(staff.getChild("salary").getText().equals("100000"))
      staff.getChild("salary").setText("7000");

      staff.removeChild("firstname");
      }
      XMLOutputter xmlOutput = new XMLOutputter();

      xmlOutput.setFormat(Format.getPrettyFormat());
      xmlOutput.output(doc, new FileWriter("D://Notes/JDOMfile.xml"));

  • SATISH

    Hi Mkyong,

    I need to convert any xml file (having complex types) in to multiple csv files with proper mappings.

    I could see lots of utilities available in .net and c#.I am using one .net utility to convert an xml in to multiple csv files.But obviously there is a restriction that we can’t use this .net library on linux platform.

    Can u please provide me any java utility (which is purely built in java) , which does the same operation.

    Or do you have any algorithm with you so that i can implement in java?

    Your help is highly appreciated , and i am constant learner of your tutorials.

    Thanks,
    Satish

  • http://techymonk.blogspot.com Ravi

    Hi, There is not FTP example. It will help me a lot if you put something.

    Best Regards
    Ravi

    • http://www.mkyong.com mkyong

      Don’t get you, what XML to do with FTP?

  • saikumar

    hi frnd,

    i have a problem with xml i.e i want to get the data from xml in the form of java objects and send those java objects into the database….can you please help me …thanks

  • http://www.dentaldoc.info Shane P

    import java.io.File;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import org.w3c.dom.*;

    I think these 4 imports are necessary when reading from XML, I got errors without these imports? Any other solutions?

    • http://www.mkyong.com mkyong

      You need it if you are using DOM to parse XML

  • http://alltutorials.in Tutorials

    Hello, Neat post. There’s an issue together with your web site in web explorer, may check this? IE still is the marketplace leader and a good part of folks will leave out your great writing due to this problem.

    • http://www.mkyong.com mkyong

      May i know what’s the problem in IE? Btw, IE is no longer leader position in web browser market.

  • http://www.desme.com Mohammed Hossain Doula

    There is not JAXB tutorial… Hopefully we will get that very soon…

    • http://www.mkyong.com mkyong

      JAXB example is added, a simple but complete example to convert object to / from XML via JAXB annotation.

  • Me

    thx… this is how example and getting started should be… straight forward…good thx

  • Pingback: Using XML()

  • http://nowebsite bill

    hi,

    so you know how to convert xml file to strings using jdom?

    thanks

    • http://www.mkyong.com mkyong

      use jdom to read the xml file and constructs any string format you want, is this what you want? Just see the above JDOM XML Parser example.

  • http://big.faceless.org java PDF

    How can I locate the Java cache, and is it safe to delete what is in it?

    • http://www.mkyong.com mkyong

      Java cache? What to do with XML?