lundi 12 mai 2014

transformer.transform doesn't work


Vote count:

0




So I am trying to run a web application that gets user input from an HTML form and appends it to an XML document on the server using Java Servlets.


Here is how I get the XML file and modify it.



@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
try {
String urlpath = "http://ift.tt/RHxpjj";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
URL url = new URL(urlpath);
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();

urlc.setDoInput(true);
urlc.setDoOutput(true);
urlc.setUseCaches(false);
urlc.setRequestMethod("GET");
urlc.setRequestProperty("Content-Type", "application / xml");

Document doc = docBuilder.parse(urlc.getInputStream());
Node m = doc.getElementsByTagName("messages").item(0);
Element messageNode = doc.createElement("message");
testMessage = request.getParameter("message-box");
if(testMessage == null) {response.sendRedirect("http://ift.tt/1iGhuHE");}
messageNode.appendChild(doc.createTextNode(testMessage));
m.appendChild(messageNode);


Here is how I write to the XML file:



if(urlc.getResponseCode() == 200) {
urlc = (HttpURLConnection) url.openConnection();
urlc.setDoOutput(true);
urlc.setUseCaches(false);
urlc.setRequestMethod("POST");
urlc.setRequestProperty("Content-Type", "application / xml");

TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", 2);
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(urlc.getOutputStream());
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.transform(source, result);
}
}catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}
response.sendRedirect("http://ift.tt/1iGhuHE");
}


No errors during compilation.


If I replace the variable "result" with System.out in the transformer.transform function, the program prints the XML file correctly and with the modification, meaning that the source isn't empty.


I know that this isn't the best way to do this, but I wouldn't do any other way right now.


Any ideas?



asked 2 mins ago






Aucun commentaire:

Enregistrer un commentaire