import java.io.*;
import org.jdom.*;
import org.jdom.output.*;
import java.util.*;
import org.jdom.input.SAXBuilder;
import org.jdom.input.DOMBuilder;
/* Study the following very carefully and write down all
comments and observations you may make. Look for
ways to simplify.
Study the following case for potential error.
Explain the error if you find any.
Input file h4jdombtest.xml ==>
You will meet a JDOM Guru today.
Sadegh Davari
You will meet a JDOM Guru today.
Sadegh Davari
Output by this program on h4jdombtest.xml ==>
COMMENT => All quotes that are fitted to show.
COMMENT => All quotes that are fitted to show.
COMMENT => another 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 commentVector=new Vector();
while(iterator.hasNext())
{
Object o = iterator.next();
//if the node is the Comment node,put it into the vector
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)
{
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
}