package com.skatestown.invoice; import java.io.File; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.CharacterData; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; /** * Check Skatestown invoice totals using a DOM parser */ public class InvoiceCheckerDOM implements InvoiceChecker { /** * Check invoice totals * @param inoviceXML Invoice XML document * @exception Exception any exception returned during processing */ public void checkInvoice(File invoiceXML) throws Exception { // Invoice running total double runningTotal = 0.0; // Obtain parser instance and parse the document DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(invoiceXML); // Calculate order subtotal NodeList itemList = doc.getElementsByTagName("item"); for (int i=0; i= .005) { throw new Exception( "Invoice error: total is " + Double.toString(total) + " while our calculation shows a total of " + Double.toString(Math.round(runningTotal * 100) / 100.0)); } } /** * Extract a double value from the text of a DOM node * @param node A DOM node with character content * @return the double representation of the node's content * @exception Exception could be the result of either a node * that doesn't have text content or a node whose text content * is not a number. */ private double doubleValue(Node node) throws Exception { // Get the character data from the node and parse it String value = ((CharacterData) node.getFirstChild()).getData(); return Double.valueOf(value).doubleValue(); } }