import java.io.*; import org.jdom.*; import org.jdom.output.*; import java.util.*; import org.jdom.input.SAXBuilder; import org.jdom.input.DOMBuilder; // No documentation. // too many space lines. // Need to use recursion. Only print out second and third level comments. public class h4q1 { public static void main(String[] argv) { if(argv.length !=1) { System.err.println("Usage: java h4q1 xmlfilename"); System.exit(1); } org.jdom.Element jdomElement=null; //Start parsing the xml file try { SAXBuilder saxBuilder = new SAXBuilder(); DOMBuilder domBuilder = new DOMBuilder(); DOMOutputter domOutputter = new DOMOutputter(); Document jdomDocument = saxBuilder.build(new File(argv[0]) ); org.w3c.dom.Element domElement = domOutputter.output(jdomDocument.getRootElement()); jdomElement = domBuilder.build(domElement); } catch(JDOMException e) { e.printStackTrace(); } catch(NullPointerException e) { e.printStackTrace(); } if (jdomElement != null) { outputComment(jdomElement,argv[0]); } } private static void outputComment(Element document, String fileName) { List children = document.getContent(); Iterator iterator = children.iterator(); // Vector is not needed. Just a long string wil be fine. Vector commentVector=new Vector(); while(iterator.hasNext()) { Object o = iterator.next(); //if the node is the Comment node,put it into the vector // Handled the first level comment. if (o instanceof Comment) { commentVector.add(o); } //if the node is the Element node,continue get its content node,and fecth //the comment node and then add to the vector else if (o instanceof Element) { // Handle the second level comments. // Poor name choices. // List otherChildren = ((Element)o).getContent(); Iterator anotherIterator = otherChildren.iterator(); while(anotherIterator.hasNext()) { Object anotherObject=anotherIterator.next(); if( anotherObject instanceof Comment) { commentVector.add(anotherObject); } } } }//end of while //output the content(comment) of the vector if(commentVector.size() == 0) { System.out.println("There is no comments for the XML file "+fileName); } else { System.out.println("Comment for the XML file "+ fileName + " => \n"); for(int i=0; i " + ((Comment)(commentVector.elementAt(i)) ).getText()); } } }//end of outputComment }