Failing to write xml document



I have created a class for building and saving an xml document to file but I can not work out why the contents of the xml is empty, and why I have to save the file in the parent directory.


I am creating a Jsp/Servlet Java webservice.


The class is supposed to get a list of testimonials from a MySQL database and generate a new XML document containing the testimonial data.


I am calling the class and methods in the doPost() method of a servlet. When a user clicks a button in on a web page the xml document is generated/updated.


Here is the class:



public class XMLGenerator {

private String xmlString;
private List<Testimonial> list;
private TestimonialService ts;
private Document xmlDoc;

public XMLGenerator(TestimonialService ts){
this.ts = ts;
list = new ArrayList<>();
xmlDoc = updateXmlDocument();

}

// generate xml string
private void updateXmlString(){

xmlString = "<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" standalone=\\\"yes\\\"?>";

list.clear();
list = updateTestimonialList();

for(Testimonial test : list){
xmlString += "<testimonial>";
xmlString += "<id>" + test.getID() + "</id>";
xmlString += "<content>" + test.getTestimonial() + "</content>";
xmlString += "<author>" + test.getAuthor() + "</author>";
xmlString += "<date>" + test.getDate() + "</date>";
xmlString += "</testimonial>";
}
}

// get list of testimonials
public List<Testimonial> updateTestimonialList(){
list.clear();
try {
list = ts.getTestimonials();
}catch(SQLException e){
e.printStackTrace();
}
return list;
}

// add testimonials to xml document
public Document updateXmlDocument() {

updateXmlString();

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try
{
builder = factory.newDocumentBuilder();
xmlDoc = builder.parse( new InputSource( new StringReader( xmlString ) ) );
return xmlDoc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

// write xml file
public boolean writeXmlToFile(){
boolean success = false;
try {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();

DOMSource source = new DOMSource(xmlDoc);
StreamResult result = new StreamResult(new File("../testimonials.xml"));

transformer.transform(source, result);
success = true;
}catch(TransformerException tr){
tr.printStackTrace();
}
return success;
}
}


Two questions:


1) Why is the xmlString converting to an empty XmlDocument?


2) Why do I have to save the xml file to the parent directory and not the WEB-INF folder?


No comments:

Post a Comment