Use XPath in servlet : XML Word PDF Mp3 « Servlet « Java Tutorial


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;

public class PostServlet extends HttpServlet {

    private SAXBuilder builder = new SAXBuilder();

    private XPath nameXPath;

    private XPath yearXPath;

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        if (!"text/xml".equals(request.getContentType())) {
            response.getWriter().println("Please post as text/xml.");
        } else {
            try {
                Document doc =;
                StringBuffer buff = new StringBuffer();
                buff.append("You searched for name '" + nameXPath.valueOf(doc)
                        + "'");
                String year = yearXPath.valueOf(doc);
                if (!"notselected".equals(year)) {
                    buff.append(" and year '" + year + "'");
            } catch (JDOMException e) {
                        "Error getting search terms: " + e.getMessage());

    public void init() throws ServletException {
        try {
            nameXPath = XPath.newInstance("/search/name/text()");
            yearXPath = XPath.newInstance("/search/year/text()");
        } catch (JDOMException e) {
            throw new ServletException("Unable to create XPaths", e);

25.31.XML Word PDF Mp3
25.31.1.Send Word file to client in a Servlet
25.31.2.Send MP3 file back to client with Servlet
25.31.3.Send XML data to client
25.31.4.Display PDF based on Request Parameter
25.31.5.Send XML to client using Servlet
25.31.6.Send Pdf to client using Servlet
25.31.7.Use XPath in servlet