Another SAX Parser Question

Hi All,
I get an xml file by making an http request. The name of the DTD comes as a relative path in the response xml file.
Questions
1. Is there a way to handle this
2. I read somewhere that i could avoid looking at the DTD alltogether,
can someone show me how with a sample code.
Kind regards

Nothing seems to help, Please help,
Im using jdk1.4 A full source codee would be great.
Thanks in advance.
This is the trace and the Code follows below:
C:\codes\parser>java -classpath xerces.jar;. ReaderConnector
Initiating Connection to System URL = http://a.b.c.com:5280/vega/
request?method=login&ui=ch16132-user&pwd=pass
Connected ..
Opening Stream for reading data
Got input stream java.io.BufferedInputStream@19821f
Got reader java.io.BufferedReader@addbf1
Read login file ...
Parsing ...
Start of Login document
\vega\xml\xrf.dtd (The system cannot find the path)
Parsed
********************************3
*****Code*****
import javax.xml.parsers.*;
import org.xml.sax.*;
import java.io.*;
import java.util.*;
import java.net.*;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.*;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.Attributes;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
* @author  JAVA
* @version
public class ReaderConnector{
    public ReaderConnector() {
    /*Login URl doesnt change*/
    private  String loginUrl  = "http://a.b.c.com:5280/vega/request?method=login&ui=ch16132-user&pwd=pass";
    //private  String loginUrl  = "c://temp/test.xml";
    private String sessionId;
    public String getSessionId(){
        if(sessionId == null){
            createConnection();
            return sessionId;
        }else{
            return sessionId;
    public void createConnection() {
        DataInputStream inputStream = null;              
        BufferedReader reader = null;
         InputStream in = null;
         FileOutputStream fos= null;
         //System.setProperty("javax.xml.parsers.SAXParserFactory",  "org.apache.xerces.jaxp.SAXParserFactoryImpl");
        try {
            URL url = new URL(loginUrl);
            URLConnection connection = url.openConnection();               
            connection.setUseCaches(false);               
            System.out.println(" Initiating Connection to System URL =  " + "http://a.b.c.com:5280/vega/request?method=login&ui=ch16132-usr&pwd=pass");
            connection.connect();
            System.out.println(" Connected ..");
            System.out.println(" Opening Stream for reading data ");
             in = new BufferedInputStream (new DataInputStream (connection.getInputStream()));                                                               
            System.out.println("Got input stream "+ in);
            reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(in)));                               
            System.out.println("Got reader "+ reader);
            System.out.println("Read login file ...");
            parseStream(reader);
        }catch (Exception e) {
                System.out.println(e.getMessage());               
        }finally {
            try {
                in.close();
                    //fos.close();
                if (inputStream != null) {
                    inputStream.close();
                if(reader!=null){
                    reader.close();
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
                ex.printStackTrace();
     public void parseStream(BufferedReader br){
        System.out.println("Parsing ...");
        try{           
            /*SAXParserFactory spf = SAXParserFactory.newInstance();
            spf.setValidating(false);
            spf.setNamespaceAware(false);
            org.xml.sax.Parser sp = (org.xml.sax.Parser)spf.newSAXParser();
            //sp.isValidating(false);
            sp.setDTDHandler(new Resolver());
            //sp.setDocumentHandler(new Handler());
            InputSource iSource = new InputSource(br);
            Handler h = new Handler();
            sp.parse(iSource );            */
          XMLReader parser;
          parser = XMLReaderFactory.createXMLReader();
          parser.setContentHandler(new Handler());
         parser.setDTDHandler(new Resolver());
          parser.parse(new InputSource(br));
        }catch(Exception e){
            System.out.println(e.getMessage());
        System.out.println("Parsed");
    public static void main(String [] args){
        ReaderConnector connector = new ReaderConnector ();
        //connector.testParsing("c://temp/test.xml");
        connector.createConnection();
    private class Resolver extends DefaultHandler{
        public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
      System.err.println(publicId + " ! " + systemId);
      if (("/vega/xml/xrf.dtd").equalsIgnoreCase(systemId) || ("/vega/xml/xrf.dtd").equalsIgnoreCase(publicId))
        try {
          return new InputSource(new URL("http://a.b.c.com:5280"+systemId).openStream());
        } catch (MalformedURLException e) {
          throw new SAXException(e);
        } catch (IOException e) {
          throw new SAXException(e);
      else return null;
    private class Handler extends org.xml.sax.helpers.DefaultHandler{                      
        public void startDocument() throws org.xml.sax.SAXException {
            System.out.println("Start of Login document");           
        public void endDocument() throws org.xml.sax.SAXException {           
            System.out.println("End of document");
        public void ignorableWhitespace(char[] values, int param, int param2) throws org.xml.sax.SAXException {
        public void endElement(java.lang.String str, java.lang.String str1, java.lang.String str2) throws org.xml.sax.SAXException {
            System.out.println("End of element reached: str, str1, str2 "+ str + " , "+ str1 + " , "+ str2);
            System.out.println("Session ID "+ sessionId);
        public void skippedEntity(java.lang.String str) throws org.xml.sax.SAXException {           
        public void processingInstruction(java.lang.String str, java.lang.String str1) throws org.xml.sax.SAXException {           
        public void startElement(java.lang.String str, java.lang.String str1, java.lang.String str2, org.xml.sax.Attributes attributes) throws org.xml.sax.SAXException {                            
            if(("A").equals(str2)){
                for(int i=0; i< attributes.getLength();i++){
                    System.out.println("Attribute "+ i + ", Name, Value "+ attributes.getQName(i) + ", " + attributes.getValue(i));
                    if(("v").equalsIgnoreCase(attributes.getQName(i)))
                        sessionId = attributes.getValue(i);
        public void endPrefixMapping(java.lang.String str) throws org.xml.sax.SAXException {
        public void startPrefixMapping(java.lang.String str, java.lang.String str1) throws org.xml.sax.SAXException {
        public void characters(char[] values, int param, int param2) throws org.xml.sax.SAXException {           
            String s =  new String(values);
            String text = s.substring(param, param+param2);                       
        public void setDocumentLocator(org.xml.sax.Locator locator) {
XML File
  <?xml version="1.0" encoding="ISO-8859-1" ?>
  <!DOCTYPE XRF (View Source for full doctype...)>
- <XRF r="2.11.1" c="" g="" u="ch16132-user" k="" d="20050614" t="151146">
  <A k="i0005" n="3" v="1964216949" />
  </XRF>
****When you view source*******
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE XRF SYSTEM "/vega/xml/xrf.dtd">
<XRF r="2.11.1" c="" g="" u="ch16132-user" k="" d="20050614" t="151722">
<A k="i0005" n="3" v="350287547"/>
</XRF>

Similar Messages

  • XML - SAX Parsing Question

    Hi,
    I am parsing XML using SAX parser and fill the values into the HashTable ( like Key value pair ).. so i can get the vaues for a particular key using hash get function.
    For the following XML. There are 2 "subscriberNumber" attribute, one is under "sn:Subscriber" and the another is under "sn:SubscriberChange".
    I can able to put this values in hash table and when i print the Hash table it is printing as sn:subscriberNumber=[1234567890, 1234567890] .. But how will i know which one is from "sn:Subscriber" and which is from "sn:SubscriberChange"
    This is the XML :
    <sn:SubscriberNotification>
    <sn:notificationSubType>1120</sn:notificationSubType>
    <sn:Subscriber>
         <cng:PaymentType>PostPaid</cng:PaymentType>
         <sn:subscriberNumber>1234567890</sn:subscriberNumber>
    </sn:Subscriber>
    <sn:SubscriberChange>
         <sn:subscriberNumber>1234567890</sn:subscriberNumber>
    </sn:SubscriberChange>
    </sn:SubscriberNotification>
    Any suggestion and pointers are really helpful
    Thanks,
    -Raj..

    Try something like this:
    import java.util.Stack;
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;
    class MyHandler extends DefaultHandler {
        Stack openTags = new Stack();
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            if (qName.equals("sn:subscriberNumber")) {
                String parentTag = (String)openTags.peek();
                System.out.println("Parent tag of this <sn:subscriberNumber> is : <" + parentTag + ">");
            openTags.push(qName);
        public void endElement(String uri, String localName, String qName) throws SAXException {
            openTags.pop();
    }Regards

  • Java sax parsing question

    Hi All,
    Any help is appreciated. Is it possible to start parsing an XML document somewhere in the middle of the document using SAX parser? It will still parse the doc sequentially but has to start at a specified location or sorts instead of starting from the beginning.
    Thanks in advance.

    Sure. Open an InputStream on the document (a FileInputStream or whatever is convenient). Read the part of the InputStream before the document and ignore the data. When you have the InputStream's cursor pointing at the beginning of the document, pass it to the parser.

  • Thread/SAX parser question

    I have a program that parses an XML document using a SAX parser. It reads the XML files that are in a given directory /home/user/input. So if there are three files it will parse the files in order, one at a time. I want it to process multiple files at the same time.
    Current it�s
    Public class ProcessFile extends DefaultHandler
    How could I use Thread since I�m extending DefualtHandler for the parser?

    SAX should mask the fact that some content is specified inside of a CDATA section.. It is just characters.
    The safest way to process characters is to setup a StringBuffer or equivalent in the startElement method. There is a variation of the StringBuffer append method that has the same three parameters (char[], int, int) as the characters signature. The characters method may be called many times before you are given all of the content of the string. How it decides when to call you depends on the parser and is subject to change over time. But, if you accumulate the contents in each call of characters and do the toString() in the endElement method you are going to get the right content. Lots of people over the last year or so that I've been involved in this forum have had other ways they thought were better than this, but most of them have eventually tried and accepted this way because it works and their "better" way did not.
    It looks like you got the content for the CDATA section (Please refer...).I'm not sure what your problem is.
    Dave Patterson

  • Interesting SAX Parser Question

    I am running a BEA Sample weblogic server and trying to parse in XML using SAX.The endElement in the sample program to parse the XML takes only one parameter like follows
    public void endElement(String name) throws SAXException {
    its not taking the local name.. in that case what should i do .. i won;t get the local name
    I tried to change it to as follows
    public void endElement(String namespaceURI, String localName,
    String name)throws SAXException
    and printing the localName.. its always empty.
    The sample code extends like this..
    public class RequestHandler extends DefaultHandler {
    Will it make any difference ? If i extend from ContentHandler will it solve the problem ? .. Please help me
    Thanks,
    -Raj..

    Thanks sir and figured that out earlier itself..
    My question now is why i am not getting the "localName" in startElement & endElement function when i extend my class using DefaultHandler ?
    I know if the Namespace is false or not present i won't get the localName.
    But my XML has namespace .. and i get the "localName" when i extend the class using ContentHandler .. at the same time when i extend my class using DefaultHandler i am not getting the "localName" .. Do i need to explicity perform the Namespace processing ??
    I am confused why i am getting localName when i extend from ContentHandler & not when i extend it from DefaultHandler ?
    class MyHandler extends DefaultHandler {
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    // localName is always empty here
    public void endElement(String uri, String localName, String qName) throws SAXException {
    // localName is always empty here
    class MyHandler extends ContentHandler {
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    //localName has Expected Value
    public void endElement(String uri, String localName, String qName) throws SAXException {
    //localName has Expected Value
    This is the XML i have :
    <?xml version="1.0" encoding="UTF-8"?>
    <SubscriberNotification xmlns:cng="http://cs.com/CSI/Namespaces/Types/Public/DataModel.xsd"
    xmlns="http://cs.com/Namespces/Container/JMS/SubscriberNotification.xsd"
    xmlns:sn="http://cs.com/Namespaces/Container/Public/SubscriberNotification.xsd"
    xmlns:mh="http://cs.com/Namespaces/Container/Public/MessageHeader.xsd">
    <mh:TrackingMessageHeader>
    <cng:version>v3</cng:version>
    </mh:TrackingMessageHeader>
    <sn:SubscriberNotification>
    <sn:DateTime>2003-12-10T11:17:27.377Z</sn:DateTime>
    <sn:Subscriber>
    <sn:subscriberNumber>1234567890</sn:subscriberNumber>
    </sn:Subscriber>
    </sn:SubscriberNotification>
    </SubscriberNotification>

  • SAX Parsing Question

    During SAX Validation, is there a way to create custom error messages that get put in the SAXParseExceptions?
    I don't want to re-implement Schema Validation. Is there a call back method I can impement and register that gets called when a SAXParseException gets generated so that I can stuff my own message in there?

    You can create a customised SAX error handler by using the ErrorHandler interface and then providing your own implementations for the standard error(), warning(), and fatalError() methods. Then, just register this error handler with your main SAX processing program.
    For example:
    import org.xml.sax.ErrorHandler;
    import org.xml.sax.SAXParseException;
    import org.xml.sax.SAXException;
    public class ErrorChecker implements ErrorHandler {
         public ErrorChecker() {
         public void error (SAXParseException e) {
              System.err.println("[Error] " +
                           getLocationString(e) + ": " +
                           e.getMessage());
         public void warning (SAXParseException e) {
              System.err.println("[Warning] " +
                                     getLocationString(e) + ": " +
                                     e.getMessage());
         public void fatalError (SAXParseException e) throws SAXException {
              System.err.println("[Fatal Error] " +
                           getLocationString(e) + ": " +
                           e.getMessage());
              throw e;
         private String getLocationString(SAXParseException e) {
              StringBuffer str = new StringBuffer();
              String systemId = e.getSystemId();
              if (systemId != null) {
                   int index = systemId.lastIndexOf('/');
                   if (index != -1)
                        systemId = systemId.substring(index + 1);
                   str.append(systemId);
              str.append(':');
              str.append(e.getLineNumber());
              str.append(':');
              str.append(e.getColumnNumber());
              return str.toString();
    }

  • SAX Parser in OC4J

    I'm trying to read a XML file in an EJB using a SAX parser.
    I tried the following statement to create the reader
    XMLReader xr = XMLReaderFactory.createXMLReader("oracle.xml.parser.v2.SAXParser");
    but I obtain the following exception:
    java.lang.ClassNotFoundException: oracle.xml.parser.v2.SAXParser
    at org.xml.sax.helpers.XMLReaderFactory.createXMLReader(XMLReaderFactory.java:118)
    The same works correctly from a command line application outside OC4J.
    Is there another SAX Parser I can use in OC4J?
    Andrea Mattioli

    I'm also seeing the a similar problem trying to get my EJB to parse SAX using the Xerces parser. If I do
    XMLReader myReader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
    and place xerces.jar into $(OC4J_INSTALL_ROOT)\j2ee\home\lib then at runtime I get
    java.lang.ClassNotFoundException: org.apache.xerces.parsers.SAXParser
    This is despite the fact that calling Class.forName() on the same class name works fine. Setting the system property org.xml.sax.driver and calling createXMLReader with no parameters results in the same error.
    I can force use of the Xerces SAX parser by bypassing the factory and just calling
    XMLReader myReader = new org.apache.xerces.parsers.SAXParser();
    but that seems a tad hacky and I don't want to hardwire SAX parser implementation choice into my code.
    Is this a known bug?
    Also which parser is getting used by default in OC4J i.e. if I don't set org.xml.sax.driver and use the no parameters variant of createXMLReader()?
    Thanks
    Alan

  • Question on SAX Parser: retrieving child

    Hi,
    I am using SAX parser to parse the XML file, because the XML file size are huge. But here i need to retrieve the child nodes of the element. Is it possible with SAX parser to retrieve the child nodes? (Like DOM parser getChildNodes method)
    Thanks in advance.

    No, of course not. When you use SAX you write the code that stores the information. So if you need the child nodes, then write code that collects all child nodes.

  • Question on SAX Parsing?

    Hi,
    How to Find end element of sax parser had parsed all the elements in the xml .
    Thanks in advance.

    906738 wrote:
    I am able to read and proccess all the data in the xml. I need to find the end element method has finished parsing all the elements in the xml file.endElement() method will be called when the parser encounters an end tag. You need to find a logic to count the number of parsed elements in endElement() method.

  • Report Result error Sax parser returned an exception

    Hi,
    I'm using Oracle Business Intelligence 10.1.3.4.2.
    Recently I changed the BI instance to another server. So that I copied the reports from Old server to New server.
    Reports are working fine in new server. But while trying to modify that reports it is showing error
    "Sax parser returned an exception. Message: Invalid character (Unicode: 0x13), Entity publicId: , Entity systemId: , Line number: 1, Column number: 10737"
    Error Codes: UH6MBRBC:E6MUPJPH
    Regards,
    Satya

    Hi Satya,
    I am facing the same issue. but I am facing this issue with Mozilla Firefox browser only. If I modify same reports in internet explorer I don't get this error.  It seems this issue is with OBIEE 10g version only and Oracle has provided some patches on this in OBIEE 11g .
    You have posted this question long back. If you have got any solution for this then please let me know also.
    Thanks

  • How to deal with empty tags in a SAX Parser

    Hi,
    I hope someone can help me with the problem I am having!
    Basically, I have written an xml-editor application. When an XML file is selected, I parse the file with a SAX parser and save the start and end locations of all the tags and character data. This enables me to display the xml file with the tags all nicely formatted with pretty colours. Truly it is a Joy To Behold. However, I have a problem with tags in this form:
    <package name="boo"/>
    because the SAX parser treats them like this:
    <package name = boo>
    </package>
    for various complex reasons the latter is unaccetable so my question is: Is there some fiendishly clever method to detect tags of this type as they occur, so that I can treat them accordingly?
    Thanks,
    Chris

    I have spent some time on googling for code doing this, but found nothing better, than I had to write in by myself.
    So, it would be something like this. Enjoy :)
    package comd;
    import org.xml.sax.helpers.DefaultHandler;
    import org.xml.sax.SAXException;
    import org.xml.sax.Attributes;
    import java.util.Stack;
    import java.util.Enumeration;
    public class EmptyTagsHandler extends DefaultHandler {
         private StringBuilder xmlBuilder;
         private Stack<XmlElement> elementStack;
         private String processedXml;
         private class XmlElement{
              private String name;
              private boolean isEmpty = true;
              public XmlElement(String name) {
                   this.name = name;
              public void setNotEmpty(){
                   isEmpty = false;
         public EmptyTagsHandler(){
              xmlBuilder = new StringBuilder();
              elementStack = new Stack();
         private String getElementXPath(){
              StringBuilder builder = new StringBuilder();
              for (Enumeration en=elementStack.elements();en.hasMoreElements();){
                   builder.append(en.nextElement());
                   builder.append("/");
              return builder.toString();
         public String getXml(){
              return processedXml;
         public void startDocument() throws SAXException {
              xmlBuilder = new StringBuilder();
              elementStack.clear();
              processedXml = null;
         public void endDocument() throws SAXException {
              processedXml = xmlBuilder.toString();
         public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
              if (!elementStack.empty()) {
                   XmlElement elem = elementStack.peek();
                   elem.setNotEmpty();
              xmlBuilder.append("<");
              xmlBuilder.append(qName);
              for (int i=0; i<attributes.getLength();i++){
                   xmlBuilder.append(" ");
                   xmlBuilder.append(attributes.getQName(i));
                   xmlBuilder.append("=");
                   xmlBuilder.append(attributes.getValue(i));
              xmlBuilder.append(">");
              elementStack.push(new XmlElement(qName));
         public void endElement(String uri, String localName, String qName) throws SAXException {
              XmlElement elem = elementStack.peek();
              if (elem.isEmpty) {
                   xmlBuilder.insert(xmlBuilder.length()-1, "/");
              } else {
                   xmlBuilder.append("</");
                   xmlBuilder.append(qName);
                   xmlBuilder.append(">");
              elementStack.pop();
         public void characters(char ch[], int start, int length) throws SAXException {
              if (!elementStack.empty()) {
                   XmlElement elem = elementStack.peek();
                   elem.setNotEmpty();
              String str = new String(ch, start, length);
              xmlBuilder.append(str);
         public void ignorableWhitespace(char ch[], int start, int length) throws SAXException {
              String str = new String(ch, start, length);
              xmlBuilder.append(str);
    }

  • Why are all the events in the XML SAX parser not activated?

    Hi everyone,
    I have written a mini server that parses XML files into SQL queries.
    Below is a segment of my code;
              try          {                                                       
                   Class.forName( JDBC_DRIVER );
                   myConnection = DriverManager.getConnection( DATABASE_URL, "username", "password");                                                  
                   EventXMLParser myEXP = new EventXMLParser(directory, myConnection);
                   File[] xmlFiles = directory.listFiles();
                   for (File xmlFile : xmlFiles)               {     
                        myEXP.XMLtoDB(xmlFile);
                        outWriter.println("File:" + xmlFile.getName() + " DONE");
              } catch (SQLException e)     {
                   System.err.println("SQLException for establishing connection");
                   e.printStackTrace();
              } catch (ClassNotFoundException e)     {
                   System.err.println("CLASS NOT FOUND EXCEPTION HERE");
                   e.printStackTrace();
              } catch (Exception e)     {
                   System.err.println(e);
                   e.printStackTrace();
              finally {
                   outWriter.println("PARSING COMPLETED");
                   outWriter.close();
         }Where the constructor EventXMLParser constructs the following:
         public EventXMLParser(File path, Connection connection)     {
              super();
              try     {
                   this.XMLpath = path;
                   this.db_connection = connection;
                   this.xr = XMLReaderFactory.createXMLReader();
                   this.XMLSAXhandler  = new DefaultHandler(); //create a new own handler
                   this.xr.setContentHandler(XMLSAXhandler);
                   this.xr.setErrorHandler(XMLSAXhandler);
                   //System.out.println("DEBUG: db_connection is " + db_connection.toString());
              catch (Exception e)     {
                   System.out.println("Constructor Error!");
                   e.printStackTrace();
         }Below are all my helper methods within EventXMLParser.java
         public void XMLtoDB(String XMLpath) throws Exception  {
              try     {
                   //Input
                   System.out.println("XMLpath is : " + XMLpath);
                   /*FileReader r = new FileReader(XMLpath); debug
                   InputSource in = new InputSource(r);
                   xr.parse(in);
                   xr.parse(XMLpath);
                   /* Note that while parsing, the end of each event, </event>
                    * will trigger sendSQL to execute the query on the database
              catch (Exception e)     {
                   throw new Exception("Error with XMLtoDB!! Exception: " + e);
         public void sendSQL(Event event, Connection sql_connection) throws SQLException     {
                   //JDBC part
                   try     {
                        System.err.println("DEBUG sendSQL");
                        Statement sql_statement = sql_connection.createStatement();
                        ResultSet resultSet = sql_statement.executeQuery( event.toSQL() );
                   catch (SQLException e)     {
                        e.printStackTrace();
         /* Parsing XML
          * From here onwards it's all designed for the SAX Parsing with different event calling methods
         public void startDocument()     {
              System.err.println("Start Document");
         public void endDocument()     {
              System.err.println("End Document");
         public void startElement(String uri, String name, String qName, Attributes atts)     {
              CurrentElement= name;
              System.out.println("This is parsing");
         public void characters(char ch[], int start, int length)     {
              SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
              StringBuffer sb = new StringBuffer();
              for (int i = start; i < start + length; i++)     
                   sb.append(ch);
              String content = sb.toString();
              if (CurrentElement.equals("eid"))
                   temp.setEventID( (Integer.valueOf(content)).intValue() ) ;
              else if (CurrentElement.equals("sd"))
                   temp.setShort_description(content);
              else if (CurrentElement.equals("ld"))
                   temp.setLong_description(content);
              else if ( (CurrentElement.equals("dt")))
                   temp.setDate_Time( formatter.parse(content, new ParsePosition(0)) );
              else if (CurrentElement.equals("repeat"))
                   temp.setRepeat_pattern( (Integer.valueOf(content)).intValue() );
              else if (CurrentElement.equals("valid"))
                   temp.setValid_period(content);
              else if (CurrentElement.equals("status"))     {
                   temp.setStatus( (Integer.valueOf(content)).intValue() );
              else {}
         public void endElement(String uri, String name, String qName)     {
              System.err.println("DEBUG" + temp.toString()); /*debug*/
              if (name.equals("event"))     {
                   try     {
                        /*debug*/ temp.setUserID(1);
                        /*debug*/ System.err.println("DEBUG: " + temp.toString());
                        sendSQL(temp, db_connection);
                        //temp = new Event();
                   catch (SQLException e)     {
                        System.err.println(e);
                   }//end catch
              }//end try
    Where event is a public class Event     {
         //fields
         private int userID = 1; // = 1 only applies for testing
         private int eventID;
         private String short_description;
         private String long_description;
         private Date date_time = null;
         private int repeat_pattern;
         private String valid_period;
         private int status;     //1 for new, 0 for modification and -1 for delete
         SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
         //Constructors
         //every event requires the following: userID eventID and short_Description
         public Event(int uID, int eID, String shortDescrp)     {
              setUserID(uID);
              setEventID(eID);
              setShort_description(shortDescrp);
         public Event(int uid, int eid, String sd,
                                  String ld, Date d_t, int r_p, String v_p, int s)     {
              setUserID(uid);
              setEventID(eid);
              setShort_description(sd);
              setLong_description(ld);
              setDate_Time(d_t);
              setRepeat_pattern(r_p);
              setValid_period(v_p);
              setStatus(s);
         //set
         public void setUserID (int x)                         { this.userID = x ;}
         public void setEventID (int x)                         { this.eventID = x ;}
         public void setShort_description (String x)          { this.short_description = x ;}
         public void setLong_description (String x)          { this.long_description = x ;}
         public void setDate_Time(Date x)                    { this.date_time = x ;}
         public void setRepeat_pattern (int x)               { this.repeat_pattern = x ;}
         public void setValid_period (String x)               { this.valid_period = x ;}
         public void setStatus (int x)                         { this.status = x; }
         //get
         public int           getUserID()                              { return this.userID;}
         public int           getEventID()                         { return this.eventID;}
         public String      getShort_description()               { return this.short_description;}
         public String      getLong_description()               { return this.long_description;}
         public Date        getDate_Time()                         { return this.date_time;}
         public int         getRepeat_pattern()                    { return this.repeat_pattern;}
         public String      getValid_period()                    { return this.valid_period;}
         public int           getStatus()                              { return this.status; }
         //Event to SQL statements;
         public String toSQL()     {
              StringBuffer sb = new StringBuffer();
              ///if ( status == 1)     {
                   sb.append( "INSERT INTO events SET" );
                   sb.append( " userID = " + userID + ", ");
                   sb.append( "eventID = " + eventID + ", " );
                   sb.append( "short_description = " + "\'" + short_description + "\'" + ", "); //String
                   sb.append( "long_description = " + "\'" + long_description + "\'"  + ", "); //String
                   sb.append( "date_time = " + "\'" + formatter.format(date_time) + "\'" + ", ");
                   sb.append( "repeat_pattern = " + repeat_pattern + ", " );
                   sb.append( "valid_period = " + "\'" + valid_period + "\'" ); //String
                   sb.append( ";");
              //} else if ( status == 2)      {
              System.err.println(sb.toString());
              return sb.toString();
    }     My question is: I have taken my SQL query generated by toSQL() method in events and it worked.
    Here is the funny thing:
    Everything is correct syntax wise: No complaints what soever
    The mysql part works: Tested separately.
    So I tend to think that the problem lies within the SAX parser. I have written SAX2 parsers on this machine before and they have worked too. I tried inserting println statements all over startElement endElement etc etc only to find out that the SAX parser did not call any of the methods that I overided!! Why is that so?
    Can you guys spot where my SAX parser fails?

    I see.
    I try to correct this problem by removing super();
    so right now my code looks like this:
         static Event temp = new Event(0, 0, "null", "null", new Date(), 0, "null", 0);
         static String CurrentElement = null;
         static File XMLpath;
         static Connection db_connection;
         static XMLReader xr;
         static DefaultHandler XMLSAXhandler; 
         //Constructor,      Build the SAX Parser
         public EventXMLParser(File path, Connection connection)     {
              try     {
                   this.XMLpath = path;
                   this.db_connection = connection;
                   this.xr = XMLReaderFactory.createXMLReader();
                   this.XMLSAXhandler  = new DefaultHandler(); //create a new own handler
                   this.xr.setContentHandler(XMLSAXhandler);
                   this.xr.setErrorHandler(XMLSAXhandler);
                   //System.out.println("DEBUG: db_connection is " + db_connection.toString());
              catch (Exception e)     {
                   System.out.println("Constructor Error!");
                   e.printStackTrace();
         }This time, I created a new instance of default handler() which can be referenced by as the objects's XMLSAXhandler. However, that did not solve the problem, why does the problem still persist?
    Right now, there is only one instance of a default handler created. So why does all my parsing event functions still get ignored?

  • SAX Parser

    I am using the sax parser provided by the package javax.xml.parsers to parse an XML file. It works fine as long as I have an XML file which has English characters. When I use it for parsing a file which has Korean characters in it, the parser fails to recognize them.
    It used to throw an error "Line too long" on reading the Korean characters. Then I added an XML directive encoding="EUC-KR" and now it reads the file but does not recognize the characters correctly. It reads all the korean characters as question marks ('??').
    Any pointers on what can be done to fix this problem.
    Thanks,
    RahulJ

    Hi,
    We've got a very similar problem. I'm parsing with SAX and DOM but the MS special characters keep appearing as ? or ??.
    If the encoding is not specified in the XML file there are Parser Exceptions. If I set the encoding to "JISAutoDetect", "JIS", "MS932", "Cp1250 to Cp1258" or "ISO8859-1" then there are no exceptions but the stray characters still appear as ?s.
    I managed to display the left and the right quotation marks in a servlet by setting the response Content Type to "text/html; charset=Shift_JIS" and the encoding="Cp1252" in the XML file. But I still have problems with the rest of the characters.
    What kind of output do you use? Do you display in a web page or you just write to a file?
    Thanks,
    Ross

  • Using the SAX Parser

    As I reported in this thread: Carriage Returns in XSLT output I am trying to produce a text output file with each line terminating in cr-lf (using the output from ViewObject.writeXML() passed through the XSLProcessor.processXSL() method to apply a XSLT stylesheet transformation to it), but the cr characters in the stylesheet are being converted to nl characters, so I am ending up with two nl characters at the end of each line.
    I found a 2002 query (here: http://www.xslt.com/html/xsl-list/2002-04/msg00193.html) by someone with the same problem, and a reply by Steve Muench explaining it and stating that the Oracle SAX parser does not have the same problem.
    So my question now is - does the SAX parser still retain cr characters (or is it too now converting them to nl) and if it does, how do I make XSLProcessor.processXSL() use it rather than the default XML parser? Can I do it from within my code, or does it need to be set in some sort of environment variable? We are on version 9.0.5.2 of JDeveloper(10g)

    Repost

  • How to get a specific tag value from SAX parser

    I am using the SAX method to parse my xml file.
    My Question is how to get the returning characters parsed after calling?
    esp the value of <body> tag?
    Here is my xml file, and i want to get the parsed <body> value after call sax parser.
    <?xml version="1.0" encoding="UTF-8"?>
    <article>
    <content>
    <title>floraaaaa</title>
    <date>2004-03-19</date>
    <body>
    Details of an article, and i want to get the article details
    </body>
    </content>
    </article>

    here is the parser code I am using:
    import java.io.*;
    import org.apache.xerces.parsers.SAXParser;
    import org.xml.sax.Attributes;
    import org.xml.sax.ContentHandler;
    import org.xml.sax.ErrorHandler;
    import org.xml.sax.Locator;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.xml.sax.XMLReader;
    import org.xml.sax.helpers.XMLReaderFactory;
    public class test2 {
         public String m_xmlDetail;
         public void readDetail(String url) {
              System.out.println("Parsing XML File: " + url + "\n\n");
              try {
                   XMLReader parser = new SAXParser();
                   ContentHandler contentHandler = new MyContentHandler();
                   parser.setContentHandler(contentHandler);
                   parser.parse(url);
              } //try ends here
              catch (IOException e) {
                   System.out.println("Error reading URI: " + e.getMessage());
              } //catch ends here
              catch (SAXException e) {
                   System.out.println("Error in parsing: " + e.getMessage());
              } //catch ends here
         } //function
    }//close class
    public class MyContentHandler implements ContentHandler {
         private Locator locator;
         //public String m_bodyDetail=new String();
         public void setDocumentLocator(Locator locator) {
              System.out.println(" * setDocumentLocator() called");
              this.locator = locator;
         public void startDocument() throws SAXException {
              System.out.println("Parsing begins...");
         public void endDocument() throws SAXException {
              System.out.println("...Parsing ends.");
         public void processingInstruction(String target, String data)throws SAXException {
              System.out.println("PI: Target:" + target + " and Data:" + data);
         public void startPrefixMapping(String prefix, String uri) {
              System.out.println("Mapping starts for prefix " + prefix + " mapped to URI " + uri);
         public void endPrefixMapping(String prefix) {
              System.out.println("Mapping ends for prefix " + prefix);
         public void startElement(String namespaceURI, String localName,String rawName, Attributes atts)throws SAXException {
              System.out.print("startElement: " + localName);
              if (!namespaceURI.equals("")) {
                   System.out.println(" in namespace " + namespaceURI + " (" + rawName + ")");
              else {
                   System.out.println(" has no associated namespace");
              for (int i=0; i<atts.getLength(); i++)
                   System.out.println(" Attribute: " + atts.getLocalName(i) +"=" + atts.getValue(i));
         public void endElement(String namespaceURI, String localName, String rawName) throws SAXException {
              System.out.println("endElement: " + localName + "\n");
         public void characters(char[] ch, int start, int end) throws SAXException {
              String s = new String(ch, start, end);
              System.out.println("characters: " + s);
         public void ignorableWhitespace(char[] ch, int start, int end)throws SAXException {
              String s = new String(ch, start, end);
              System.out.println("ignorableWhitespace: [" + s + "]");
         public void skippedEntity(String name) throws SAXException {
              System.out.println("Skipping entity " + name);
    } //close class

Maybe you are looking for

  • Deletion files

    hi i have a very strange problem, so the application is swing app, i use intellij IDEA this is only informative.It is for uploading files to ftp, at the end of the process i must delete files, the problem is that the last one file doesn't delete.The

  • HP LP3065 - problems selecting input

    Dear people, Quite some time ago I purchased the LP3065 monitor, it has always worked perfectly well. Until recently II had only one PV with DVI output. No matter which of the inputs on the monitor I connected the cable to, it worked perfectly well.

  • ITunes Video Compared to DVD on MBP?

    I want Scrubs season 5 on DVD. But season 4 comes out in October so who knows when season 5 will be out. It's available on iTunes but I am concerned about the quality. If I download the season, will it compare to DVD quality on my MBP? I found this w

  • Flex 4 DataVisualization

    We were working on implementing a ui with Flex 4. The problem is that we need the DataVisualization portion for the AdvancedDataGrid and Charting. When will this be available? I need a date as we were humming on all cylinders are now blocked by this

  • Macbook pro 13 2012 graphical glitches

    Processor  2.9 GHz Intel Core i7 Memory  16 GB 1600 MHz DDR3 Graphics  Intel HD Graphics 4000 1024 MB Software  OS X 10.9 (13A603) when I insert a dvd and the dvd player starts automatically or when entering time machine this used to  happen more oft