gvsu/cs675/dom_sax/JDOM.java
josh 10f6e8ea4a DOM working
git-svn-id: svn://anubis/gvsu@123 45c1a28c-8058-47b2-ae61-ca45b979098e
2008-06-10 22:13:13 +00:00

114 lines
3.6 KiB
Java

import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.util.HashMap;
import java.io.*;
public class JDOM
{
public static void main(String args[])
{
if (args.length != 1)
{
System.err.println("Usage: java JDOM <XMLFile>");
return;
}
JDOM j = new JDOM();
j.parse(args[0]);
}
private HashMap<String, String> m_weekDayNames;
public JDOM()
{
m_weekDayNames = new HashMap<String, String>();
m_weekDayNames.put("sunday", "Sunday");
m_weekDayNames.put("monday", "Monday");
m_weekDayNames.put("tuesday", "Tuesday");
m_weekDayNames.put("wednesday", "Wednesday");
m_weekDayNames.put("thursday", "Thursday");
m_weekDayNames.put("friday", "Friday");
m_weekDayNames.put("saturday", "Saturday");
}
public void parse(String file)
{
Document doc = null;
try
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(file);
if (doc != null)
printHTMLSchedule(doc, System.out);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
private void printHTMLSchedule(Node n, PrintStream out)
{
int type = n.getNodeType();
switch (type)
{
case Node.DOCUMENT_NODE:
out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"");
out.println("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">");
out.println("<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><title>Daily Planner</title>");
out.println("<style type=\"text/css\">");
out.println(" .day, th { background-color: #FF8; }");
out.println(" table, td, th { border: solid #000 1px; padding: 3px; }");
out.println("</style>");
out.println("</head><body>");
out.println("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><caption>Daily Planner</caption>\n<tr><th>&nbsp;</th><th>AM</th><th>PM</th></tr>");
printHTMLSchedule( ((Document) n).getDocumentElement(), out );
out.println("</table>\n</body>\n</html>");
break;
case Node.ELEMENT_NODE:
String name = n.getNodeName();
NodeList children = n.getChildNodes();
if (name.equals("dailyplanner"))
{
for (int i = 0; i < children.getLength(); i++)
printHTMLSchedule(children.item(i), out);
}
else if (m_weekDayNames.containsKey(name))
{
out.print("<tr><td class=\"day\">");
out.print(m_weekDayNames.get(name));
out.print("</td>");
for (int i = 0; i < children.getLength(); i++)
{
if (children.item(i).getNodeType() == Node.ELEMENT_NODE)
{
out.print("<td>");
printAMPM(children.item(i), out);
out.print("</td>");
}
}
out.println("</tr>");
}
break;
}
}
private void printAMPM(Node n, PrintStream out)
{
NodeList children = n.getChildNodes();
for (int i = 0; i < children.getLength(); i++)
{
Node c = children.item(i);
if (c.getNodeType() == Node.TEXT_NODE)
{
out.print(c.getNodeValue());
}
}
}
}