SAX Parser within a Servlet

Hi,

Can someone guide me on how to make a SAX Parser within a Servlet, I would be grateful if someone could provide sample code.

Many Thanks
dr_alinaeemAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Kevin CrossChief Technology OfficerCommented:
liviutudorCommented:
well what are you trying to achieve with the sax parser in your servlet?
dr_alinaeemAuthor Commented:
Thanks for the links, but what I am trying to do is to run a SAX parser on Java Servlet, which will give the output in html
HTML5 and CSS3 Fundamentals

Build a website from the ground up by first learning the fundamentals of HTML5 and CSS3, the two popular programming languages used to present content online. HTML deals with fonts, colors, graphics, and hyperlinks, while CSS describes how HTML elements are to be displayed.

liviutudorCommented:
well why don't you use XSL and convert the file on the fly to html?
dr_alinaeemAuthor Commented:
well what are you trying to achieve with the sax parser in your servlet?

I am going to parse the xml file in my servlet, when the servlet comes accross a particulat tag such as, <ask>, then my servlet will prompt the user.
liviutudorCommented:
when you say "prompt the user" what do you mean? Just show a textarea in the html page?
dr_alinaeemAuthor Commented:
I mean, when the servlet comes across the tag <ask>, the servlet will then display the message on the html page. The message will be the element in side the <ask></ask>, is it possible?
Kevin CrossChief Technology OfficerCommented:
Sounds like you want this to be interactive.  You may be better off, parsing with XSL up front as was suggested, so you take an XML document that lays out form, then user can post form to your Servlet for final processing and output.
liviutudorCommented:
it is. you need to implemet a class like this:
public class AskScanner extends DefaultHandler
{
private insideAsk = false;
private List<String> results=new ArrayList<String>();
private StringBuilder sb = null;
public void startElement(String uri,String localName,String qName,Attributes attributes)
{
if(qName.equals("ask")) {
insideAsk=true;
sb = new StringBuilder();
}
}

public void endElement(String uri,String localName,String qName)
{
if(qName.equals("ask")) {
insideAsk=false;
results.add( sb.toString() );
}
}

public void characters(char[]buf,int start,int len)
{
if( insideAsk) sb.apeend( buf, start,len);
}

public List<String> getResults()
{
return results;
}
}

So basically at the end of the execution of this parser results will contain the list of all the stuff inside all the <ask> elements.
dr_alinaeemAuthor Commented:
Thanks liviutudor, but i have tried to complie/execute the class and it does not execute, When executing do i specify the name of xml file on the command line?
Kevin CrossChief Technology OfficerCommented:
good thought liviutudor.

Notes on above if you are going to use it:
...
private List<String> results=new ArrayList<String>();
// List<Type> and ArrayList<String> are only valid with JRE 5, so ensure you set compliance level properly in IDE
...
if( insideAsk) sb.apeend( buf, start,len);
// sb.apend versus sb.apeend
...
Kevin CrossChief Technology OfficerCommented:
SAXParser parser = new SAXParser();
parser.setContentHandler(AskScanner);
parser.setErrorHandler(AskScanner);
String url = {filepath_to_xml}
parser.parse(url);

Kevin CrossChief Technology OfficerCommented:
keep in mind you may have to use try/catch blocks and trap on SAXExceptions that may occur.
dr_alinaeemAuthor Commented:
so how would this work together?
liviutudorCommented:
sorry about the typos, mwvisa1 -- and apologies to dr_alinaeem for not posting the bit of code that triggers the scanner -- mwvisa1's one seems fine though, you can use that bit of code to scan the file through my class.
dr_alinaeemAuthor Commented:
I thankyou so much for your help, but I am still a little clueless of where to put the scanner, can u please show me, as i will look to increase points, also will the xml file need to be entered on the command line?
Kevin CrossChief Technology OfficerCommented:
No need for apologies Liviutudor (I was merely trying to head off any issues trying to execute your solution which looked like a good one).
dr_alinaeem, as Liviutudor stated, you would put code I showed above in your Servlet's dopost/doget method or however you implementing servlet taking action and just create another class that can be a part of servlet class or separate and then ensure your import statements are correct for all the classes needed and you should compile and be able to try.
Kevin CrossChief Technology OfficerCommented:
Put the XML file in a folder on server accessible by Servlet.

Will need these imports
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import org.apache.xerces.parsers.SAXParser;

public class AServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
      public void doGet(HttpServletRequest request,
                  HttpServletResponse response) throws ServletException, IOException {
performAction(request, response);
      }

      public void doPost(HttpServletRequest request,
                  HttpServletResponse response) throws ServletException, IOException {
            performAction(request, response);
      }

      protected void performAction(HttpServletRequest request,
                  HttpServletResponse response) throws ServletException, IOException {
            ...
SAXParser parser = new SAXParser();
parser.setContentHandler(AskScanner); // Might have to mke AServlet.AskScanner
parser.setErrorHandler(AskScanner);
String url = {filepath_to_xml}
parser.parse(url);
...
      }                  

// can make static so only one copy of class ever made since embedding inside servlet which is called more than once
public static class AskScanner extends DefaultHandler
{
private insideAsk = false;
private List<String> results=new ArrayList<String>();
private StringBuilder sb = null;
public void startElement(String uri,String localName,String qName,Attributes attributes)
{
if(qName.equals("ask")) {
insideAsk=true;
sb = new StringBuilder();
}
}

public void endElement(String uri,String localName,String qName)
{
if(qName.equals("ask")) {
insideAsk=false;
results.add( sb.toString() );
}
}

Can also create a new file just for AskScanner class called AskScanner.java and put in same package as servlet or however code is organized.

public void characters(char[]buf,int start,int len)
{
if( insideAsk) sb.apeend( buf, start,len);
}

public List<String> getResults()
{
return results;
}
}

}

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
dr_alinaeemAuthor Commented:
Thanks a lot... I used the following code as follows...

import javax.servlet.*;
import javax.servlet.http.*;
import org.xml.sax.*;
import javax.servlet.http.HttpSession.*;
import org.xml.sax.helpers.DefaultHandler;
import org.apache.xerces.parsers.SAXParser;

public class AServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
     public void doGet(HttpServletRequest request,
               HttpServletResponse response) throws ServletException, IOException {
performAction(request, response);
     }

     public void doPost(HttpServletRequest request,
               HttpServletResponse response) throws ServletException, IOException {
          performAction(request, response);
     }

     protected void performAction(HttpServletRequest request,
               HttpServletResponse response) throws ServletException, IOException {

SAXParser parser = new SAXParser();
parser.setContentHandler(AskScanner); // Might have to mke AServlet.AskScanner
parser.setErrorHandler(AskScanner);
String url = {filepath_to_xml}
parser.parse(url);

     }                

// can make static so only one copy of class ever made since embedding inside servlet which is called more than once
public static class AskScanner extends DefaultHandler
{
private insideAsk = false;
private List<String> results=new ArrayList<String>();
private StringBuilder sb = null;
public void startElement(String uri,String localName,String qName,Attributes attributes)
{
if(qName.equals("ask")) {
insideAsk=true;
sb = new StringBuilder();
}
}

public void endElement(String uri,String localName,String qName)
{
if(qName.equals("ask")) {
insideAsk=false;
results.add( sb.toString() );
}
}

but it is not compiling :-(
Kevin CrossChief Technology OfficerCommented:
Sorry wasn't paying attention to exact code as was just an example.
Copy and pasted original post Liviutudor.  Code coming...
Kevin CrossChief Technology OfficerCommented:
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.sun.org.apache.xerces.internal.parsers.SAXParser;

public class AServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
     public void doGet(HttpServletRequest request,
               HttpServletResponse response) throws ServletException, IOException {
performAction(request, response);
     }

     public void doPost(HttpServletRequest request,
               HttpServletResponse response) throws ServletException, IOException {
          performAction(request, response);
     }

     protected void performAction(HttpServletRequest request,
               HttpServletResponse response) throws ServletException, IOException {

           AskScanner handler = new AskScanner();
SAXParser parser = new SAXParser();
parser.setContentHandler(handler); // Might have to mke AServlet.AskScanner
parser.setErrorHandler(handler);
String url = "c:/xml.xml";
try {
      parser.parse(url);
} catch (SAXException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
} catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
}

     }                

     public static class AskScanner extends DefaultHandler
     {
     private boolean insideAsk = false;
     private List<String> results=new ArrayList<String>();
     private StringBuilder sb = null;
     public void startElement(String uri,String localName,String qName,Attributes attributes)
     {
     if(qName.equals("ask")) {
     insideAsk=true;
     sb = new StringBuilder();
     }
     }

     public void endElement(String uri,String localName,String qName)
     {
     if(qName.equals("ask")) {
     insideAsk=false;
     results.add( sb.toString() );
     }
     }

     public void characters(char[]buf,int start,int len)
     {
     if( insideAsk) sb.append( buf, start,len);
     }

     public List<String> getResults()
     {
     return results;
     }
     }

}
dr_alinaeemAuthor Commented:
Thanks a lot, however I am trying to access the servlet with the following html code, but it does not seem to be working, I have also put the xml file in the same classes folder as the AServlet.java file, still not working :-(
 
<html>
<head>
<title>
Servlet Parser
</title>
</head>
<body>
<form name='parse' method='get' action='/servlet/AServlet'>
<input type="submit" value='Next'>
</form>
</body>
</html>
dr_alinaeemAuthor Commented:
its just gives an empty output
Kevin CrossChief Technology OfficerCommented:
This might be obvious question, but have you altered the code to our specific environment, especially putting in proper path to the XML file you are trying to parse?
Kevin CrossChief Technology OfficerCommented:
And also need to write code to display XML how you want it.

Once you are done, use the usual methodology to write to response stream.
dr_alinaeemAuthor Commented:
sorry that was my mistake, but i have got the xml file path set and the program seems to execute without any errors. Could you please advise me on how to out the results() which were captureed by the parser.
Kevin CrossChief Technology OfficerCommented:
I may be a bit rusty on this, but think you just call getResults() method to variable within your performAction method then you format into your string for HTML by iterating through List object item values.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java EE

From novice to tech pro — start learning today.