import javax.servlet.http.*; import oracle.xml.parser.v2.*; import org.w3c.dom.*; import org.xml.sax.SAXException; import java.net.URL; import javax.servlet.ServletException; import java.io.*; public class XMLUpperCaseStringServlet extends HttpServlet { // Handle the HTTP POST request protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { XMLDocument incomingXMLDoc = null; // Tell the requester she's getting XML in response resp.setContentType("text/xml"); // Get the character writer to write the response into PrintWriter out = resp.getWriter(); try { // If we're receiving posted XML if (req.getContentType().equals("text/xml")) { // Get the InputStream on the HTTP POST request's request body InputStream incomingXMLStream = req.getInputStream(); // Parse it with our helper incomingXMLDoc = XMLHelper.parse(incomingXMLStream,null); // Find any <String> elements in the posted doc using selectNodes NodeList stringElts = incomingXMLDoc.selectNodes("//String"); // Loop over any matching nodes and uppercase the string content int matches = stringElts.getLength(); for (int z=0; z<matches; z++) { Text t = (Text)stringElts.item(z).getFirstChild(); // Uppercase the node value of the first text-node Child t.setNodeValue(t.getNodeValue().toUpperCase()); } // Write posted XML doc (with <String>'s now uppercased) to response incomingXMLDoc.print(out); } else out.println("<error>You did not post an XML document</error>"); } catch (SAXException s) { out.println("<error>You posted an ill-formed XML document"); } catch (XSLException x) { out.println("<error>Error processing selectNodes"); } } } |