01: import java.io.File;
02: import java.io.IOException;
03: import java.util.ArrayList;
04: import javax.xml.parsers.DocumentBuilder;
05: import javax.xml.parsers.DocumentBuilderFactory;
06: import javax.xml.parsers.ParserConfigurationException;
07: import javax.xml.xpath.XPath;
08: import javax.xml.xpath.XPathExpressionException;
09: import javax.xml.xpath.XPathFactory;
10: import org.w3c.dom.Document;
11: import org.xml.sax.SAXException;
12: 
13: /**
14:    An XML parser for item lists
15: */
16: public class ItemListParser
17: {
18:    /**
19:       Constructs a parser that can parse item lists
20:    */
21:    public ItemListParser() 
22:          throws ParserConfigurationException
23:    {
24:       DocumentBuilderFactory dbfactory 
25:             = DocumentBuilderFactory.newInstance();
26:       builder = dbfactory.newDocumentBuilder();
27:       XPathFactory xpfactory = XPathFactory.newInstance();
28:       path = xpfactory.newXPath();
29:    }
30: 
31:    /**
32:       Parses an XML file containing an item list
33:       @param fileName the name of the file
34:       @return an array list containing all items in the XML file
35:    */
36:    public ArrayList<LineItem> parse(String fileName) 
37:       throws SAXException, IOException, XPathExpressionException
38:    {
39:       File f = new File(fileName);
40:       Document doc = builder.parse(f);
41: 
42:       ArrayList<LineItem> items = new ArrayList<LineItem>();
43:       int itemCount = Integer.parseInt(path.evaluate(
44:             "count(/items/item)", doc));
45:       for (int i = 1; i <= itemCount; i++)
46:       {
47:          String description = path.evaluate(
48:                "/items/item[" + i + "]/product/description", doc);
49:          double price = Double.parseDouble(path.evaluate(
50:                "/items/item[" + i + "]/product/price", doc));
51:          Product pr = new Product(description, price);
52:          int quantity = Integer.parseInt(path.evaluate(
53:                "/items/item[" + i + "]/quantity", doc));
54:          LineItem it = new LineItem(pr, quantity);
55:          items.add(it);
56:       }
57:       return items;
58:    }
59: 
60:    private DocumentBuilder builder;
61:    private XPath path;
62: }
63: 
64: 
65: 
66: 
67: 
68: 
69: 
70: 
71: