/** *Class DomEcho *@author Martin Carlsson Internetprogrammering 4 Course */ import javax.xml.parsers.*; import org.w3c.dom.*; import java.io.*; import org.xml.sax.*; /** *DOM Echo creates and writes a DOM-träd the output of choice by the use of XMLSerializer. *@see XMLSerializer */ public class DomEcho { /** Parses the result and echos it back if it's well-formed. */ void parseEcho(String xmlFilename, String outputSource) { try { File xmlFile = new File(xmlFilename); Document document = null; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.parse(xmlFile); XMLSerializer xmlSerializer = new XMLSerializer(); if(outputSource.trim().equals("System.out")) xmlSerializer.serialize(document, System.out); else xmlSerializer.serialize(document, new File(outputSource)); } catch (SAXException e) { System.err.println("\n" + xmlFilename + " is not wellformed!"); System.exit(1); } catch (IOException e) { System.err.println(e); System.exit(1); } catch(ParserConfigurationException e) { System.err.println(e); System.exit(1); } } /** *Main. */ public static void main(String[] args) throws Exception { String resultText = null; DomEcho dEcho = new DomEcho(); if(args.length == 1 && args[0].trim().equals("help") || args.length == 0) { usage(); return; } else if (args.length >= 2) { dEcho.parseEcho(args[0], args[1]); resultText = "\n\nThe file " + args[0] + " is wellformed\nEchoed content of " + args[0] + " can be found in " + args[1]; } else if(args.length == 1) { dEcho.parseEcho(args[0], "System.out"); resultText ="\n\nThe file " + args[0] + " is wellformed\nFinished echoing content of " + args[0]; } if(resultText != null) System.out.println(resultText); } /** Help information. */ private static void usage() { System.out.println("\n**********DomEcho usage***************************"); System.out.println("Usage: DomEcho "); System.out.println(" or"); System.out.println(" DomEcho "); System.out.println("About:"); System.out.println(" DomEcho parses the content of a xml file"); System.out.println(" and echos to stdout or to a file of choise"); System.out.println(" if the parsed file is well-formed."); System.out.println(" Default output is stdout."); System.out.println(" DomEcho help = this message"); System.out.println("****************************************************"); } } // End DomEcho