1 19 20 package org.shoppingcartconvertor; 21 22 import java.io.IOException ; 23 import java.util.Iterator ; 24 import org.netbeans.api.convertor.book.Book; 25 import org.netbeans.api.convertor.ConvertorDescriptor; 26 import org.netbeans.api.convertor.Convertors; 27 import org.netbeans.api.convertor.dvd.DVD; 28 import org.netbeans.api.convertor.shoppingcart.ShoppingCart; 29 import org.netbeans.spi.convertor.Convertor; 30 import org.w3c.dom.Document ; 31 import org.w3c.dom.Element ; 32 import org.w3c.dom.Node ; 33 import org.w3c.dom.NodeList ; 34 import org.w3c.dom.Text ; 35 import org.xml.sax.ErrorHandler ; 36 import org.xml.sax.InputSource ; 37 import org.xml.sax.SAXException ; 38 39 40 44 public class ShoppingCartConvertor implements Convertor { 45 46 private static final String NAMESPACE = "http://www.netbeans.org/ns/shoppingcart"; 47 48 public ShoppingCartConvertor() { 49 } 50 51 public Object read(org.w3c.dom.Element element) { 52 ShoppingCart sc = new ShoppingCart(); 53 NodeList nodes = element.getChildNodes(); 55 for (int i = 0; i < nodes.getLength(); i++) { 56 Node node = nodes.item(i); 57 if (node.getNodeType() == Node.ELEMENT_NODE) { 58 Element e = (Element )node; 59 if (Convertors.canRead(e)) { 60 Object o = Convertors.read(e); 61 if (o instanceof Book) { 62 sc.addBook((Book)o); 63 } else if (o instanceof DVD) { 64 sc.addDVD((DVD)o); 65 } else { 66 System.err.println("Shopping cart contains unknown item: "+o); 68 } 69 } else { 70 System.err.println("Shopping cart contains item which cannot be convertor: "+e); 72 } 73 } 74 } 75 return sc; 76 } 77 78 public org.w3c.dom.Element write(Document doc, Object inst) { 79 ShoppingCart sc = (ShoppingCart)inst; 80 Element element = doc.createElementNS(NAMESPACE, "shoppingcart"); 81 82 Iterator it = sc.books.iterator(); 83 while (it.hasNext()) { 84 Object o = it.next(); 85 Element e = Convertors.write(doc, o); 86 element.appendChild(e); 87 } 88 89 it = sc.dvds.iterator(); 90 while (it.hasNext()) { 91 Object o = it.next(); 92 Element e = Convertors.write(doc, o); 93 element.appendChild(e); 94 } 95 96 return element; 97 } 98 99 } 100 | Popular Tags |