import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; class Page { public static final String CLASS_NAME = Page.class.getName(); public static final String ATTRIBUTE_NAME_ID = "id"; public static final String TAG_NAME_TITLE = "Title"; public static final String TAG_NAME_FILE = "File"; private String id = null; private String title = null; private String file = null; // default public Page() { } // field parameters public Page(String id, String title, String file) { this.id = id; this.title = title; this.file = file; } // element public Page(Element element) { // id this.id = element.getAttribute(ATTRIBUTE_NAME_ID); // title NodeList nodeListTitle = element.getElementsByTagName(TAG_NAME_TITLE); for (int i = 0; i < nodeListTitle.getLength(); i++) { Element elementTitle = (Element)nodeListTitle.item(i); this.title = elementTitle.getFirstChild().getNodeValue(); } // file NodeList nodeListFile = element.getElementsByTagName(TAG_NAME_FILE); for (int i = 0; i < nodeListFile.getLength(); i++) { Element elementFile = (Element)nodeListFile.item(i); this.file = elementFile.getFirstChild().getNodeValue(); } } // xml file name public Page(String xmlName) throws Exception { try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(new File(xmlName)); Element root = document.getDocumentElement(); // root name check if (!CLASS_NAME.equals(root.getTagName())) { throw new Exception("root name error."); } // id this.id = root.getAttribute(ATTRIBUTE_NAME_ID); // title NodeList nodeListTitle = root.getElementsByTagName(TAG_NAME_TITLE); for (int i = 0; i < nodeListTitle.getLength(); i++) { Element elementTitle = (Element)nodeListTitle.item(i); this.title = elementTitle.getFirstChild().getNodeValue(); } // file NodeList nodeListFile = root.getElementsByTagName(TAG_NAME_FILE); for (int i = 0; i < nodeListFile.getLength(); i++) { Element elementFile = (Element)nodeListFile.item(i); this.file = elementFile.getFirstChild().getNodeValue(); } } catch (Exception e) { throw e; } } public void setTitle(String title) { this.title = title; } public void setFile(String file) { this.file = file; } public String toString() { return "[id=" + this.id + ", title=" + this.title + ", file=" + this.file + "]"; } }