Use XPath in servlet : JDOM « XML « Java





Use XPath in servlet

   

import java.io.IOException;

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 = builder.build(request.getReader());
                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 + "'");
                }
                buff.append(".");
                response.getWriter().print(buff.toString());
            } catch (JDOMException e) {
                response.getWriter().print(
                        "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);
        }
        super.init();
    }
}

   
    
  










Related examples in the same category

1.Simple demo of JDOM
2.Read an XML document using JDOM
3.Use JDOM to build a document
4.Make up and write an XML document, using JDOMMake up and write an XML document, using JDOM
5.List an XML file after building it into a JDOM DocumentList an XML file after building it into a JDOM Document
6.Simple example of using JDOM
7.Use Unchecked JDOM Factory
8.JDom: Locating a speech with the findCharactersFirstSpeech() method
9.Use JDOM to change the element text
10.JDOM: transform
11.Parsing with JDOM
12.Accessing Attributes Using JDOM
13.Creating a Document Using JDOM
14.Adding an Element Using JDOM
15.Adding an Attribute Using JDOM
16.Outputting a Document Using XMLOutputter
17.Use SAXBuilder from JDOM
18.Create document from jdom
19.Add elements to root element
20.Get child from root
21.XPath with JDOM
22.NamespaceTest with JDOM
23.extends org.jdom.Element
24.Iterate through elements
25.JDOM Util
26.General XML Utility Functions For JDOM