001package edu.pdx.cs410J.xml; 002 003import org.w3c.dom.Element; 004import org.w3c.dom.NamedNodeMap; 005import org.w3c.dom.Node; 006import org.w3c.dom.NodeList; 007 008import java.util.ArrayList; 009import java.util.List; 010 011/** 012 * This class represents an entry in a phone book. It is used to 013 * demonstrate how XML DOM trees can be turned into Java objects. 014 */ 015public abstract class PhoneBookEntry { 016 protected List<String> streetLines = new ArrayList<>(); 017 protected String apt; 018 protected String city; 019 protected String state; 020 protected String zip; 021 protected String phone; // Includes area code XXX-XXX-XXXX 022 023 /** 024 * Helper method to fill in address data from a chunk of an XML DOM 025 * tree. 026 */ 027 protected void fillInAddress(Element root) { 028 NodeList elements = root.getChildNodes(); 029 for (int i = 0; i < elements.getLength(); i++) { 030 Node node = elements.item(i); 031 if (!(node instanceof Element)) { 032 continue; 033 } 034 035 Element element = (Element) node; 036 switch (element.getNodeName()) { 037 case "street": { 038 Node text = element.getFirstChild(); 039 this.streetLines.add(text.getNodeValue()); 040 break; 041 } 042 043 case "apt": { 044 Node text = element.getFirstChild(); 045 this.apt = text.getNodeValue(); 046 break; 047 } 048 049 case "city": { 050 Node text = element.getFirstChild(); 051 this.city = text.getNodeValue(); 052 break; 053 } 054 055 case "state": { 056 Node text = element.getFirstChild(); 057 this.state = text.getNodeValue(); 058 break; 059 } 060 061 case "zip": { 062 Node text = element.getFirstChild(); 063 this.zip = text.getNodeValue(); 064 break; 065 } 066 } 067 } 068 } 069 070 /** 071 * Helper method to fill in phone data from a chunk of an XML DOM 072 * tree. 073 */ 074 protected void fillInPhone(Element phone) { 075 String areacode = null; 076 String number = null; 077 078 // Examine the phone's attributes 079 NamedNodeMap attrs = phone.getAttributes(); 080 for (int i = 0; i < attrs.getLength(); i++) { 081 Node attr = attrs.item(i); 082 String nodeName = attr.getNodeName(); 083 switch (nodeName) { 084 case "areacode": 085 areacode = attr.getNodeValue(); 086 continue; 087 088 case "number": 089 number = attr.getNodeValue(); 090 continue; 091 } 092 } 093 094 this.phone = areacode + "-" + number; 095 } 096 097 public String toString() { 098 // Just make a string for the address and phone number 099 StringBuilder sb = new StringBuilder(); 100 101 for (String line : this.streetLines) { 102 sb.append(line); 103 sb.append("\n"); 104 } 105 106 if (apt != null) { 107 sb.append("Apt ").append(this.apt).append("\n"); 108 } 109 110 sb.append(this.city).append(", ").append(this.state).append(" ").append(this.zip).append("\n"); 111 sb.append(this.phone).append("\n"); 112 113 return sb.toString(); 114 } 115}