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.
Komentar
Posting Komentar