DOMDemo.java

Copyright 2001, Gerry de Koning

/*
 * Copyright 2001, Gerry de Koning
 * 
 * This program is for educational purposes only.
 * It is an example only, and not designed to be
 * fit for any other purpose.
 */
import org.w3c.dom.*;
import org.apache.xerces.parsers.*;
import org.apache.xml.serialize.*;
import org.xml.sax.InputSource;
import java.io.*;
import java.text.*;

public class DOMDemo {
	public static void main (String[] args) throws Exception {
		if (args.length != 2) {
			System.err.println(
					"Usage: java DOMDemo <inFile> <outFile>");
			System.exit(-1);
		}
		// Get a number formatter, we'll need it later
		NumberFormat fmt = NumberFormat.getInstance();
		
		// Get a DOM parser and parse the input XML file
		DOMParser parser = new DOMParser();
		parser.parse(new InputSource(new FileReader(args[0])));
		
		// Find all the <C> elements
		Document doc = parser.getDocument();
		NodeList nodes = doc.getElementsByTagName("C");
		
		// Process each <C> element found
		for(int i=0; i < nodes.getLength(); i++ ) {
			Element thisNode = (Element) nodes.item(i);
			Node parent = thisNode.getParentNode();
			
			// Get temperature and convert to Fahrenheit
			String tempC = thisNode.getFirstChild().getNodeValue();
			double tC = Double.parseDouble(tempC);
			double tF = 32.0 + (1.8 * tC);
			fmt.setMaximumFractionDigits(
				(tempC.indexOf(".") != -1) ? 1 : 0);
			String tempF = fmt.format(tF);
			
			// Create a new node to hold 
			Element newNode = doc.createElement("F");
			newNode.appendChild(doc.createTextNode(tempF));
			parent.appendChild(newNode);
		}
		
		// Write out the DOM to a new XML file
		XMLSerializer out = new XMLSerializer(
		                       new FileWriter(args[1]),
		                       new OutputFormat("XML", "utf-8",
		                       					true));
		out.serialize(doc);
	}