1 import java.util.ArrayList;
2 import javax.xml.parsers.DocumentBuilder;
3 import javax.xml.parsers.DocumentBuilderFactory;
4 import javax.xml.parsers.ParserConfigurationException;
5 import org.w3c.dom.Document;
6 import org.w3c.dom.Element;
7 import org.w3c.dom.Text;
8
9 /**
10 Builds a DOM document for an array list of items.
11 */
12 public class ItemListBuilder
13 {
14 private DocumentBuilder builder;
15 private Document doc;
16
17 /**
18 Constructs an item list builder.
19 */
20 public ItemListBuilder()
21 throws ParserConfigurationException
22 {
23 DocumentBuilderFactory factory
24 = DocumentBuilderFactory.newInstance();
25 builder = factory.newDocumentBuilder();
26 }
27
28 /**
29 Builds a DOM document for an array list of items.
30 @param items the items
31 @return a DOM document describing the items
32 */
33 public Document build(ArrayList<LineItem> items)
34 {
35 doc = builder.newDocument();
36 doc.appendChild(createItems(items));
37 return doc;
38 }
39
40 /**
41 Builds a DOM element for an array list of items.
42 @param items the items
43 @return a DOM element describing the items
44 */
45 private Element createItems(ArrayList<LineItem> items)
46 {
47 Element e = doc.createElement("items");
48
49 for (LineItem anItem : items)
50 e.appendChild(createItem(anItem));
51
52 return e;
53 }
54
55 /**
56 Builds a DOM element for an item.
57 @param anItem the item
58 @return a DOM element describing the item
59 */
60 private Element createItem(LineItem anItem)
61 {
62 Element e = doc.createElement("item");
63
64 e.appendChild(createProduct(anItem.getProduct()));
65 e.appendChild(createTextElement(
66 "quantity", "" + anItem.getQuantity()));
67
68 return e;
69 }
70
71 /**
72 Builds a DOM element for a product.
73 @param p the product
74 @return a DOM element describing the product
75 */
76 private Element createProduct(Product p)
77 {
78 Element e = doc.createElement("product");
79
80 e.appendChild(createTextElement(
81 "description", p.getDescription()));
82 e.appendChild(createTextElement(
83 "price", "" + p.getPrice()));
84
85 return e;
86 }
87
88 private Element createTextElement(String name, String text)
89 {
90 Text t = doc.createTextNode(text);
91 Element e = doc.createElement(name);
92 e.appendChild(t);
93 return e;
94 }
95 }