DOM - Java working with XML overview (tutorial)

Complete Source Code for all examples below

Points to consider:

  • All DOM is loaded into memory as Document object
  • Should not be use for very large files
  • Should be used when data to be extracted from the document is not known and we need to retrieve it from Document object e.g. through XPath
  • Should be used if you wish to make alterations to the document.

 

Simple Example:

We need to load an XML document in java.

 

The XML:

 



  
    PIPE
    Smoking pipe
    10.90
    10
  
  
    VIO
    Violin
    99.99
    5
  



The code to do the task:

 

package dp.test.xml.jaxp.dom;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import dp.test.xml.xpath.XPathExample;

/**
 * JAXP Dom allows to load the full DOM model into memory straight away.
 * The benefits are that you can work with the in memory loaded document
 * as you wish, which is good for when you do not know exactly what you will need 
 * from the document (e.g. you want to use XPath to extract the data later on) 
 * or if you are likely to manipulate the document (i.e. edit it). This all comes 
 * at the cost of memory space.
 * 
 * @author DPavlov
 */
public class JAXPDomExample
{

	@Test
	public void testDomLoad() throws ParserConfigurationException, SAXException, IOException {
		
		// Use DOM API to get full XML document
		DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
		Document document = docBuilder.parse(XPathExample.class.getResourceAsStream("stock.xml"));
		
		final StringBuilder out = new StringBuilder();
		appendNode(out, document, 0); // Document is in itself also a Node
		
		System.out.println(out.toString());
		
	}
	
	private void appendNode(final StringBuilder toAppendTo, final Node node, final int deep) {
		
		for (int i = 0; i < deep - 1; i++) {
			toAppendTo.append(" |");
		}
		toAppendTo.append(" +->").append(node.getNodeName());
		if (node.getChildNodes().getLength() > 0) {
			toAppendTo.append('\n');
			for (int ii = 0; ii < node.getChildNodes().getLength(); ii++) {
				appendNode(toAppendTo, node.getChildNodes().item(ii), deep + 1);
			}
		} else {
			toAppendTo.append(": ").append(node.getTextContent().replaceAll("\n", "")).append('\n');
		}
		
	}
	
}

 

The output of the above code:

 +->#document
 +->warehouse
 | +->#text:   
 | +->stock
 | | +->#text:     
 | | +->symbol
 | | | +->#text: PIPE
 | | +->#text:     
 | | +->name
 | | | +->#text: Smoking pipe
 | | +->#text:     
 | | +->price
 | | | +->#text: 10.90
 | | +->#text:     
 | | +->quantity
 | | | +->#text: 10
 | | +->#text:   
 | +->#text:   
 | +->stock
 | | +->#text:     
 | | +->symbol
 | | | +->#text: VIO
 | | +->#text:     
 | | +->name
 | | | +->#text: Violin
 | | +->#text:     
 | | +->price
 | | | +->#text: 99.99
 | | +->#text:     
 | | +->quantity
 | | | +->#text: 5
 | | +->#text:   
 | +->#text: 

Summary:

  • Use DocumentBuilderFactory factory to get instance of DocumentBuilder
  • Use parse method of DocumentBuilder to create Document object
This page was last updated on: 13/04/2012 11:08