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

About the Author

author image
mkyong
Founder of Mkyong.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

avatar
40 Comment threads
20 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
44 Comment authors
loaderraton kumar mongolArjun vasudevanvijaybeginnerstutorialexamples Recent comment authors
newest oldest most voted
raton kumar mongol
Guest
raton kumar mongol

oh

loader
Guest
loader

I would pull and dumb a load on that sad face

Arjun vasudevan
Guest
Arjun vasudevan

I am trying to write ‘>’ special character to xml using transformer factory in java. I am using EscapeUtils.escapeXml from commons.lang for escaping.

what it does is, it ecapes the string twice.

> as ” & g t ;” (without space, for printing purpose i m writing like this)
again
&, in & g t , as & amp ;
so i get the final string as
& amp ; gt ;

how do i escape only once.
> as & gt ;

Thanks in advance
:)

vijay
Guest
vijay

can you update jaxb with database
how to get the data from db to xml and display the response
like..

PARAM_NAME PARAM_VALUE
ABC 23
DEF 343

If PARAM_NAME as ABC , we have to get 23 value
like…

23

beginnerstutorialexamples
Guest
beginnerstutorialexamples

Good XML explanation.

Visit beginnerstutorialexamples.com for more Java XML and parsing tutorial with examples.

http://www.beginnerstutorialexamples.com/xml-parser-in-java-tutorial-example/

LAZCOOL
Guest
LAZCOOL

Hi. Help me please. How to display informations in an array from a XML code. I have not any idea…

Rupesh Patil
Guest
Rupesh Patil

How to convert following XML file to array and insert this array into database

8839

9123456789

Mr

FirstName

MidName

LastName

Male

-00011130

2014

07

1

9066

0

0

0

NA

0

catalog

4320

11729

4320

CoEP – Executive Health Chk Up – Male

0

8840

9876543210

Ms

testFirstName

testMidName

testLastName

Female

-00011130

2014

07

1

9067

0

0

0

NA

0

catalog

4319

11728

4319

CoEP – Executive Health Chk Up – Female

0

4320

11727

4320

CoEP – Executive Health Chk Up – Female_2

0

JOHN PETER.R
Guest
JOHN PETER.R

how to read xml data without parser using java?

Java Guru
Guest
Java Guru

http://codesnippets4all.com/html/parsers/home.htm

have lot of ready to use code snippets on dom, sax, stax, jdom, google gson, quick-json, json simple parsers

edddy
Guest
edddy

how to delete XML file present in a directory

vara prasad
Guest
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.

Gonzalo Abollado
Guest
Gonzalo Abollado

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

Gonzalo.

Android Guru
Guest
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
Guest
XYZ

ur site helps a lot

Nirmal
Guest
Nirmal
Saurabh Kapoor
Guest
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
Guest
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
Guest
amit

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

Collin
Guest
Collin

Very Helpful Tutorials!

ganeshkumar.t
Guest
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

rafat
Guest
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
Guest
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
Guest
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

bradyliu
Guest
bradyliu

I like it

Rupesh Patil
Guest
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

trackback
Read a XML file with Java

[…] You should choose the correct XML parsers to read or parse XML file, like DOM or SAX, refer to this Java XML tutorials, a good start. Reply With Quote « Previous Thread | Next […]

Ramulu
Guest
Ramulu

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

Yajairo87
Guest
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
Guest
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
Guest
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
Guest
Tomas

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

Darshan
Guest
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
Guest
ramarajan

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

mkyong reader
Guest
mkyong reader

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

Satish
Guest
Satish

Using XMLBeans and JAXB.

Satish
Guest
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
Guest
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);… Read more »

Shridharan
Guest
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"));