Java XML Tutorial

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.
- Read a XML file
Read a XML file and print it out each elements. - Modify existing XML file
Modify an existing XML file, by update the element and attribute, and also how to delete a element. - Create a new XML file
Create a XML file with new document, element and attribute. - Count XML Elements
Search and count total number of elements in a XML file.
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.
- Read a XML file
Read a XML file via SAX callback methods. - Read a UTF-8 XML file
Read a Unicode XML file via SAX callback methods. - SAX Error – Invalid byte 1 of 1-byte UTF-8 sequence
Common SAX error for XML file which contains Unicode character. - SAX Error – Content is not allowed in prolog
Common SAX error for invalid XML file content.
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.
- Read a XML file
Read a XML file and print it out each elements. - Modify existing XML file
Modify an existing XML file, by update the element and attribute, and also how to delete a element. - Create a new XML file
Create a XML file with new document, element and attribute.
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
- Wiki Java_API_for_XML_Processing
- DOM XML parser documentation
- JDOM XML parser
- SAX useful quick start example
- SAX XML parser documentation
- JAXB Official Website
- Properties documentation
- Processing XML with Java

How do we implement code for validation in java ???
Very Helpful Tutorials!
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
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
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
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
Use JDBC to read/from database, and XML parser for XML data. What’s your problem?
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.
Learn XML parsers like DOM or SAX to read the data from XML file.
Learn JDBC to write data into database.
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
I like it
Hello sir
I need help
sir i want java code that read xml file where tag name of xml file is unknown.
thanks
how to display all the missing tags and exceptions while validating a xml against xsd
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
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.
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 :)
Some people are trying their whole life, sometimes to do both.
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?
try using DOM Parser and set type=”all” in the
How can we convert any xml to Java object? looking for generalized solution?
Using XMLBeans and JAXB.
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.
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.
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"));
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
Hi, There is not FTP example. It will help me a lot if you put something.
Best Regards
Ravi
Don’t get you, what XML to do with FTP?
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
Hi saikumar,
You can use XmlBeans.You can read xml as a java object
Hi saikumar,
You can use XmlBeans.You can read xml as a java object.
please refer this :http://www.ibm.com/developerworks/xml/library/x-beans1/
its helped me lot.
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?
You need it if you are using DOM to parse XML
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.
May i know what’s the problem in IE? Btw, IE is no longer leader position in web browser market.
There is not JAXB tutorial… Hopefully we will get that very soon…
JAXB example is added, a simple but complete example to convert object to / from XML via JAXB annotation.
thx… this is how example and getting started should be… straight forward…good thx
hi,
so you know how to convert xml file to strings using jdom?
thanks
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.
How can I locate the Java cache, and is it safe to delete what is in it?
Java cache? What to do with XML?