1 import java.io.File;
2 import java.io.IOException;
3 import java.util.ArrayList;
4 import javax.xml.parsers.DocumentBuilder;
5 import javax.xml.parsers.DocumentBuilderFactory;
6 import javax.xml.parsers.ParserConfigurationException;
7 import javax.xml.xpath.XPath;
8 import javax.xml.xpath.XPathExpressionException;
9 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 private DocumentBuilder builder;
19 private XPath path;
20
21 /**
22 Constructs a parser that can parse item lists.
23 */
24 public ItemListParser()
25 throws ParserConfigurationException
26 {
27 DocumentBuilderFactory dbfactory
28 = DocumentBuilderFactory.newInstance();
29 builder = dbfactory.newDocumentBuilder();
30 XPathFactory xpfactory = XPathFactory.newInstance();
31 path = xpfactory.newXPath();
32 }
33
34 /**
35 Parses an XML file containing an item list.
36 @param fileName the name of the file
37 @return an array list containing all items in the XML file
38 */
39 public ArrayList<LineItem> parse(String fileName)
40 throws SAXException, IOException, XPathExpressionException
41 {
42 File f = new File(fileName);
43 Document doc = builder.parse(f);
44
45 ArrayList<LineItem> items = new ArrayList<LineItem>();
46 int itemCount = Integer.parseInt(path.evaluate(
47 "count(/items/item)", doc));
48 for (int i = 1; i <= itemCount; i++)
49 {
50 String description = path.evaluate(
51 "/items/item[" + i + "]/product/description", doc);
52 double price = Double.parseDouble(path.evaluate(
53 "/items/item[" + i + "]/product/price", doc));
54 Product pr = new Product(description, price);
55 int quantity = Integer.parseInt(path.evaluate(
56 "/items/item[" + i + "]/quantity", doc));
57 LineItem it = new LineItem(pr, quantity);
58 items.add(it);
59 }
60 return items;
61 }
62 }
63
64
65
66
67
68
69
70
71