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

Similar Messages

  • 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>

  • XML SAX parser that support  LexicalHandler

    Hello,
    I'm looking for an XML SAX parser that support a LexicalHandler.
    I have xml files that are not well formed, ie: (&, <, >, etc...) characters within tags and I need to ignore them.
    Anyone have a link to some opensource library ??
    Thanks,
    Samir

    Don't waste your time. Using a LexicalHandler isn't going to help with parsing malformed XML. You should get the person who produced those files to replace them with correct XML.
    PC&#178;

  • Trying to use XML SAX parser with JDK2 ...

    Hi,
    I'm pretty new to Java.
    I'm trying to write and use java sample using XML SAX parser. I try with XP and XML4J.
    Each time I compile it give me a error message like
    "SAX01.java:23: unreported exception java.lang.Exception; must be caught or declared to be
    thrown
    (new SAX01()).countBooks();
    ^
    Note: SAX01.java uses or overrides a deprecated API.
    Note: Recompile with -deprecation for details.
    1 error"
    For what I found, it seems that "deprecated" mean usage of old classes or methods. What should I do ?
    Wait for the XML parser to be rewrite ? ....
    Thank's
    Constant

    "SAX01.java:23: unreported exception
    java.lang.Exception; must be caught or declared to be
    thrown
    (new SAX01()).countBooks();
    ^Do this
    public static void main(String[] args) throws Exception {
    or do this
         try
                       first part of expression?(new SAX0()).countBooks();
         catch(Exception ex)     
              System.out.println("problem "+ ex);
    Note: SAX01.java uses or overrides a deprecated API.
    Note: Recompile with -deprecation for details.
    1 error"deprecation is just a warning if there are no errors elsewhere in your program it should compile fine, but if you want to find out how to change it do this:
    javac YourClassName.java -deprecation
    then look in the docs for an alternative.

  • 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?

  • Xml sax parser

    Hi all,
    I am newbie to xml. I am using SAX parser for parsing xml documents. I have to write a code which parses all types of xsd files(including which can contain inline , referenced or both). Can anyone help / guide me how to code a generic xsd parser??
    Thanks in advance,

    An XSD file is an XML file, so you can parse it using sax.
    See :
    http://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/sax/2a_echo.html
    http://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/sax/work/Echo02.java
    See also:
    http://www.oracle.com/technology/tech/xml/xdk/doc/production/java/doc/java/javadoc/oracle/xml/parser/schema/XMLSchema.html#getXMLSchemaNodeTable

  • 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

  • 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();
    }

  • 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>

  • Java +XML (SAX) Parser for Oracle 8.1.5 EE

    Hi there :)
    I am looking java classes for SAX to parse XML. I cannot find a valid parser, cause after downloaded from Oracle XDK for java, when i try to load this calasses i get a messages that i alot of classes connot be resolved.
    If somebody have valid classes on Ora 8.1.5 please send me mail.
    Adam

    Have i possibilities to using some javatypes in oracle java stored procedure if this class is not loaded into db?
    Cause i would like to create a java stored procedure to parse and insert some data from xml. I was thinking to pass xml file name as a parameter to my java procedure.
    I must use Oracle 8.1.5 with jdk 1.1.7, and the best parser for me is SAX.
    Please help.
    Have i possobilities to use class inside oracle, which are placed outside oracle?
    Something like classpath, where can i modify value (but classpath inside oracle)?

  • Sax Parser for loading XML file

    We have a requirment by which we need to load huge XMl file in our DB everyday.
    THe XML file format is like --
    <?xml version="1.0" encoding="UTF-8"?>
    <root>
    <emp>
    <ename>aaa</ename>
    <sal>3000</sal>
    </emp>
    <emp>
    <ename>bbb</ename>
    <sal>5000</sal>
    </emp>
    <dept>
    <name>productiong</name>
    <location>USA</location>
    <dept>
    I have written XMl SAX parser to load this file into DB -
    import org.xml.sax.helpers.DefaultHandler;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.XMLReader;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.xml.sax.Attributes;
    import java.io.*;
    import java.sql.*;
    import oracle.jdbc.driver.*;
    import oracle.xml.sql.*;
    import oracle.sql.*;
    import oracle.jdbc.*;
    import oracle.jdbc.pool.OracleDataSource;
    import java.util.*;
    public class test extends DefaultHandler
    String thisElement="";
    String table_name="";
    String table_name_2="";
    String sql="";
    String value_clause="";
    StringBuffer value_clauseBuffer;
    String Insert_sql="";
    int flag;
    String columnNames="";
    String questionmarks="";
    static String conStr = "jdbc:oracle:thin:@abcd1234:1521:dss501";
    static Connection conn;
    String arrayValues[] = new String[30];
    int j = 0;
    int emptyElementFlag = 0;
    public SurveyReader() throws SQLException, FileNotFoundException, IOException{
    DBConnect("username", "password");
    public static void DBConnect(String username, String password)
    throws SQLException, FileNotFoundException, IOException {
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    conn = DriverManager.getConnection(conStr, username, password);
    conn.setAutoCommit(true);
    public void startElement(String namespaceURI, String localName,
    String qName, Attributes atts) throws SAXException {
    thisElement = qName;
    if (thisElement!=table_name){
    columnNames = columnNames + ", " + qName;
    questionmarks = questionmarks +", " + "?";
    emptyElementFlag =0;
    public void characters(char[] ch, int start, int length)
    throws SAXException {
    if (thisElement !="root"){     
    if ((length == 0) && (thisElement !="") ){
    table_name = thisElement;
    sql = " Insert into "+ table_name +"(";
    value_clause="";
    value_clauseBuffer =null;
    columnNames = "";
    questionmarks ="";
    j =0;
    if ((length != 0) && (thisElement!="") && (thisElement!=table_name)){
    emptyElementFlag = 1;
    String s = new String(ch, start, length);
    String newString = s.replaceAll("'", "''");
    // String newString = s;
    if (value_clauseBuffer== null){
    value_clauseBuffer = new StringBuffer(newString);
    else{
    value_clauseBuffer.append(newString);
    public void endElement(String namespaceURI, String localName, String qName)
    throws SAXException {
    if (thisElement !="root"){
    if ((!(value_clauseBuffer == null))||((emptyElementFlag ==0) && (qName !=table_name))) {
    try{
    //value_clauseBuffer.append("', '");
    if (value_clauseBuffer == null){
    arrayValues[j]="";
    else{
    arrayValues[j]=""+value_clauseBuffer;
    j = j+1;
    value_clauseBuffer = null;
    emptyElementFlag =0;
    }catch(Exception e){
    System.err.println(e);
    System.exit(2);
    if (qName == table_name){
    if (!(value_clauseBuffer == null)){
    value_clause = "'"+value_clauseBuffer;
    columnNames =columnNames.substring(1, columnNames.length());
    int paramNumber = j;
    questionmarks =questionmarks.substring(1, questionmarks.length());
    sql = sql + columnNames + " ) values (" + questionmarks +"); ";
    Insert_sql=Insert_sql + sql;
    sql = "Begin "+sql + " End; ";
         try{
         PreparedStatement pstat = conn.prepareStatement(sql);
    for (int i=0; i<=j-1; i++ ){
    int k = i+1;
    pstat.setObject(k, arrayValues);
         ResultSet rset = pstat.executeQuery();
         rset.close();
         pstat.close();
    catch (Exception e) {
    System.err.println(e);
    System.out.print("sql " + sql);
    System.exit(1);
    table_name_2 = table_name;
    thisElement = "";
    public static void main (String args[]) {
    XMLReader xmlReader = null;
    System.out.println("Time " + new java.util.Date());
    try {
    SAXParserFactory spfactory = SAXParserFactory.newInstance();
    spfactory.setValidating(false);
    SAXParser saxParser = spfactory.newSAXParser();
    xmlReader = saxParser.getXMLReader();
    xmlReader.setContentHandler(new SurveyReader());
    xmlReader.setErrorHandler(new SurveyReader());
    InputSource source = new InputSource("short.xml");
    xmlReader.parse(source);
    conn.close();
    } catch (Exception e) {
    System.err.println(e);
    System.exit(1);
    This parser takes 2 hours to laod file of size around 8MB.
    ANy suggestions on improving performance of the parser.
    ANy other approach I should be taking to load this file into DB.
    We are using ORacle 9i DB with Character set UTF 8.
    Thanks!

    String buf = (new String(ch, start, length)).trim();
    if (thisElement != "root"){   
    if ((buf.length() == 0) && (thisElement !="") ){
    It run ok!
    Thanks 58871!
    Now, i want to export oracle table to xml file like :
    <?xml version="1.0" encoding="UTF-8"?>
    <root>
    <emp>
    <ename>aaa</ename>
    <sal>3000</sal>
    </emp>
    <emp>
    <ename>bbb</ename>
    <sal>5000</sal>
    </emp>
    </root>
    Can SAX export to xml format?
    Pham Thanh Tung

  • Org.xml.sax error content not allowed in prolog

    Hi,
    I am running Jetty 6.x on SUSE and there is a webapp called pyjasper i am trying to run on it. the context maps fine and it displays the content however, when i use the applet in the webapp to create a report (.jasper) it gives me a org.xml.sax Parse exception: content not allowed in prolog.
    A little part of the error is pasted below:
    generating report /tmp/pyJasper/compiled-reports/6390c37d0ea810c7fae3e647c2f86817.jasper
    Parse Fatal Error at line 1 column 1: Content is not allowed in prolog.
    org.xml.sax.SAXParseException: Content is not allowed in prolog.
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:174)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:388)
    at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(XMLScanner.java:1414)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:1039)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:807)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:107)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
    at org.apache.commons.digester.Digester.parse(Digester.java:1647)
    at net.sf.jasperreports.engine.xml.JRXmlLoader.loadXML(JRXmlLoader.java:239)
    at net.sf.jasperreports.engine.xml.JRXmlLoader.loadXML(JRXmlLoader.java:226)
    at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:214)
    at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:168)
    at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:152)
    at net.sf.jasperreports.engine.JasperCompileManager.compileReportToFile(JasperCompileManager.java:115)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    2010-03-04 09:15:59.073::WARN: /pyJasper/jasper.py
    at net.sf.jasperreports.engine.xml.JRXmlLoader.loadXML(JRXmlLoader.java:243)
    at net.sf.jasperreports.engine.xml.JRXmlLoader.loadXML(JRXmlLoader.java:226)
    at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:214)
    at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:168)
    at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:152)
    at net.sf.jasperreports.engine.JasperCompileManager.compileReportToFile(JasperCompileManager.java:115)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    I am guessing this is some sort of an error in xml parsing. I found couple of solutions on sun java forums but none of them worked for me. Right now I am trying to figure out whether this is being caused by the applet or the java itself.
    Apparently other people who use this applet do not have a problem and they have the exact same files as me. So I am not sure what exactly is causing tihs problem. Bit of a noob.
    Any help would be greatly appreciated.
    THANK YOU VERY MUCH!!!! :)

    Hi thanks you very much for the reply.
    In my message I forgot to mention that I edited my prologs to "<?xml version = "1.0" encoding = "UTF-8"?>" and the jetty.xml that has the server configuration has:
    <?xml version = "1.0" encoding = "UTF-8"?>
    <!DOCTYPE Configure PUBLIC "-//Mort Bay Consulting//DTD Configure//EN" "http://jetty.mortbay.org/configure.dtd">
    I apologize for the clarity of my message. I meant to say that I was wondering whether the problem is with the xm files that java has, or the xml files that are in the pyjasper package that I downloaded?
    I also checked for byte order mark using hex editor to see if those six characters were in front of my xml files. None of the files in the pyjasper package had the BOM so that solution did not work.
    Is there something wrong with the above xml prolog?
    I have been reading tons of different posts and stuf trying to figure this out for the past month but juts cannot seem to get it to work.
    Thanks.

  • SAX Parser,setValidationMode

    We have to parse an XML of 5 MB size and load into the
    Database.We started using the DOM Parser(PL/SQL) and getting the
    Out of Memory errors.(The Java Pool Size is 250 MB).As per the
    Oracle Documentation we have stated using the SAX Parser.But
    Using SAXParser we are not able to use the "setValidationMode"
    Method.I am getting "Method setValidationMode(boolean) not found
    in interface org.xml.sax.Parser." error message.
    Can any one help me what is the problem.
    Thanks in Advance.

    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

  • SAX Parser throws NullPointerException

    Hi.
    I'm using WLS6.1 SP1 built-in XML SAX parser. The code is like,
    SAXParserFactory factory = SAXParserFactory.newInstance();
    XMLReader parser = factory.newSAXParser().getXMLReader();
    // Add a error handler
    eh = new MyErrorHandler();
    parser.setErrorHandler(eh);
    parser.setContentHandler(this);
    // Enable namespace
    parser.setFeature("http://xml.org/sax/features/namespaces", true);
    // Enable validation
    parser.setFeature("http://xml.org/sax/features/validation", false);
    parser.parse(new InputSource(in));
    The NullPointerException is thrown at -
    org.apache.xerces.framework.XMLParser.parse(XMLParser.java:965)
    after the end element of (</eb:MessageHeader>) before the start element of <SOAP-ENV:Header>.
    The XML file is attached.
    =====================================
    However, I tried to parse this document on xerces parser 131.
    It worked fine.
    =====================================
    Did I miss any thing? It seems like a bug to me.
    Thanks!
    [header.xml]

    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

Maybe you are looking for