Search for the item specified, and either create a new file or
update the existing one. DOM Level 2 Range is used for quicker
replacement of a range of data.
// Get parameter values
String id = req.getParameterValues("id")[0];
String name = req.getParameterValues("name")[0];
String description = req.getParameterValues("description")[0];
// See if this file exists
Document doc = null;
File xmlFile = new File(ITEMS_DIRECTORY + "item-" + id + ".xml");
String docNS = "http://www.oreilly.com/javaxml2";
if (!xmlFile.exists()) {
// Create new DOM tree
DOMImplementation domImpl = new DOMImplementationImpl();
doc = domImpl.createDocument(docNS, "item", null);
Element root = doc.getDocumentElement();
root.setAttribute("xmlns", docNS);
// ID of item (as attribute)
root.setAttribute("id", id);
// Name of item
Element nameElement = doc.createElementNS(docNS, "name");
Text nameText = doc.createTextNode(name);
nameElement.appendChild(nameText);
root.appendChild(nameElement);
// Description of item
Element descriptionElement = doc.createElementNS(docNS, "description");
Text descriptionText = doc.createTextNode(description);
descriptionElement.appendChild(descriptionText);
root.appendChild(descriptionElement);
} else {
// Load document
try {
DOMParser parser = new DOMParser();
parser.parse(xmlFile.toURL().toString());
doc = parser.getDocument();
Element root = doc.getDocumentElement();
// Name of item
NodeList nameElements = root.getElementsByTagNameNS(docNS, "name");
Element nameElement = (Element)nameElements.item(0);
Text nameText = (Text)nameElement.getFirstChild();
nameText.setData(name);
// Description of item
NodeList descriptionElements =
root.getElementsByTagNameNS(docNS, "description");
Element descriptionElement = (Element)descriptionElements.item(0);
// Remove and recreate description
Range range = ((DocumentRange)doc).createRange();
range.setStartBefore(descriptionElement.getFirstChild());
range.setEndAfter(descriptionElement.getLastChild());
range.deleteContents();
Text descriptionText = doc.createTextNode(description);
descriptionElement.appendChild(descriptionText);
} catch (SAXException e) {
// Print error
PrintWriter out = res.getWriter();
res.setContentType("text/html");
out.println("<HTML><BODY>Error in reading XML: " +
e.getMessage() + ".</BODY></HTML>");
out.close();
return;
}
}
// Serialize DOM tree
DOMSerializer serializer = new DOMSerializer();
serializer.serialize(doc, xmlFile);
// Print confirmation
PrintWriter out = res.getWriter();
res.setContentType("text/html");
out.println("<HTML><BODY>Thank you for your submission. " +
"Your item has been processed.</BODY></HTML>");
out.close();