To SAX or not to SAX?

Hi I have created an application that parses XML documents and inserts them into the db. The problem is that files ar very big such as 50MB to 100MB. They say SAX should be used for large documnets like my case, and stop reading through the XML document once the certain data has been found and processed. In my casse I need to hadle every node and insert within a db, does it matter if I just use DOM and juice up the server computer that will handle the XML with memmory?

I guess so... The files will never be more then 100 or so MB in size, I also restrict the size if it is any higher then about 120MB. Another restriction that I have added to the application is that it will only process 1 document at a time... In this application performance is not an issue... So even if 30 documents are waiting to be processed and it takes one hour so be it....

Similar Messages

  • XML parsing -  org.xml.sax.driver not specified

    I am attempmtping to parse my first XML document and get the following excpetion when running my prog.
    org.xml.sax.SAXException: System property org.xml.sax.driver not specified.
    I am following the examples in the O'Reilly Java and XML book but suspect I am missing something obvious.
    This is the offending line of code:
    XMLReader xr = XMLReaderFactory.createXMLReader();
    Any help will be appreciated.

    You need to set a property for your class that invokes your SAX handler. This is the property you need to set
    org.xml.sax.driver=???
    Where ??? is the name of the package where your SAXparser lives.
    for example, my sax driver is in:
    org.xml.sax.driver=org.apache.xerces.parsers.SAXParser
    (see code below)
    Also, a sweet reference is Elliot Rusty Harold's "XML processing with Java", which answered all the practical questions I had -- really! And is free, online.
    http://www.ibiblio.org/xml/books/xmljava/chapters/index.html
    This is the code for main() where my xml handler is invoked
    try
    {  SpiderHandler spiderHandler = new SpiderHandler(testSpider);
       XMLReader reader = XMLReaderFactory.createXMLReader();
       reader.setContentHandler(spiderHandler);
       for (int i=4; i<args.length; i++)
       {   FileReader xmlScript = new FileReader(args);
    System.out.println("Input file number "+i+" named "+args[i]);
    // org.xml.sax.XMLReader.parse(InputSource) interface
    // see org.xml.sax.InputSource class      
    reader.parse(new InputSource(xmlScript));
    catch(Exception e)
    {   System.out.println("Error encountered in parsing from main(). \n");
    e.printStackTrace();
    Luck to you! XML is a joy.

  • System property org.xml.sax.driver not specified

    I'm getting the error:
    System property org.xml.sax.driver not specified
    How do I set this property? Why doesn't it find the default?
    I'm using WL6.0
    Imports:
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.FactoryConfigurationError;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerException;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.TransformerConfigurationException;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamSource;
    import javax.xml.transform.stream.StreamResult;
    import org.xml.sax.InputSource;
    import org.xml.sax.XMLReader;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.w3c.dom.Document;
    import org.w3c.dom.DOMException;
    Code Snippet:
    try
    File stylesheet = new File("LaborDistHours.xsl");
    LaborDistHours ldh = new LaborDistHours("1041410011",
    "01-feb-2000", "30-mar-2000");
    DocumentBuilderFactory factory =
    DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    StringReader reportXML = new StringReader( ldh.getReportXML() );
    document = builder.parse(new InputSource( reportXML ));
    TransformerFactory tFactory = TransformerFactory.newInstance();
    StreamSource stylesource = new StreamSource(stylesheet);
    Transformer transformer = tFactory.newTransformer(stylesource);
    //error occurs here
    DOMSource source = new DOMSource(document);
    StringWriter reportXLST = new StringWriter();
    StreamResult result = new StreamResult(reportXLST);
    transformer.transform(source, result);
    Steven Ford ([email protected])
    "...That we here highly resolve that these dead shall not have died in
    vain - that this nation, under God, shall have a new birth of Freedom - and
    that Government of the people, by the people and for the people shall not
    perish from the earth." Abraham Lincoln

    try to look on xml.apache.org for this error. There should be some pages describing how and why setup this property.
    Basically, these properties defines factories for javax extensions. javax defines interfaces and providers than supply implementations, so for example you can use different XML parsers implementations (we use Xalan for one OC4J container and original ORACLE parser for other). To bind this together they use some defined mechanism like setting system property of including special manifest file etc. (I don't know about details)
    Myrra

  • Where can a guy get good sax? Not in orchestra!

    I just loaded my new orchestra jampack. My main reason for the purchase was to get woodwinds. To my mind, this includes saxophones. I didn't think i needed to sift through the details since apple clearly prints a tenor sax right on the box cover (behind the harp). I thought the different images on the box were supposed to at least reflect, in part, the content of the box. But i was wrong. I am disappointed in apple. I thought they were better than what I consider to be very misleading marketing. I am wondering if anyone else out there was also duped and if apple might be persuaded to allow those who purchased orchestra to down load the saxes at no charge. What do you think?

    Sax is not a traditional orchestral instrument, although it is included in some great orchestral scores, such as Bolero. And when it is an orchestral instrument, it doesn't usually sound like a jazz, big band, rock, or pop music sax, which are styles most people associate with sax before the more rarified orchestral sax.
    What kind of sax sound were you looking for anyway, aside from the Jampack issue?
    As for the Jampack issue, I recall that it lists specific instruments on the back of the box, and the list doesn't include sax. However, as you said, the front of the box has a picture of a sax (from an artist who apparently didn't read the back of the box!). So if what you were primarily interested in was some good old fashioned sax, and you bought the Jampack based on the picture, you might have a case for return/exchange.
    If you're otherwise happy with the orchestral Jampack, and just lament the lack of sax, perhaps you could simply add that one particular sound from another source.

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

  • [CDATA] not the same way read in DOM and SAX (DOM: O.K., SAX: not O.K.)

    I wrote a test application that reads a XML file. First method reads it via DOM in a Document object, second that reads it via SAX in a string. The output is almost the same but the character data is different:
    while the dom outout is as expected:
    <hap>EUSF</hap>
    <name><![CDATA[WADDELL&REED ADV BOND CL Y]]></name>
    the SAX output is different:
    <hap>EUSF</hap>
    <name>WADDELL&REED ADV BOND CL Y</name>
    as both elements have text data, only the second is enclosed in a <![CDATA]> value. The DOM output is the same as when displayed the XML in internet explorer, so i guess this is the correct result. but my SAX reader does not display the <![CDATA]> value ...
    to get the sax output i subclassed DefaultHandler and overwrote the methods like described in the Web Service Tutorial "Echoing an XML File with the SAX Parser" (http://java.sun.com/webservices/docs/ea2/tutorial/doc/JAXPSAX3.html#64190):
    * Overwrites super.
    * Receive notification of character data inside an element.
    public void characters(char buf[], int offset, int len) {
    String s = new String(buf, offset, len);
    if (!s.trim().equals("")) { //suppress output of characters that are all whitespace
    write(s);
    }//characters()
    the characters() method has the content of an element, but it has not the information if a CDATA is enclosing the data or not(?). How can this be done?

    There's a thing called a LexicalHandler (org.xml.sax.ext.LexicalHandler) that has startCDATA and endCDATA methods. The API documentation suggests that you could create your own LexicalHandler and use it somehow, but it doesn't give you a nicely packaged example. I don't have an example of it either, sorry.
    However despite what you say, those two outputs are not different. In XML terms they are identical and parsers will treat them identically.

  • Org.xml.sax.SAXException: System property org.xml.sax.driver not specified

    Hi,
    I am running Jdeveloper 9.0.3.1 and using embedded OC4J.
    Getting following error when trying to run the application. Please help me if you can.
    Thanks
    Tareq
    at org.xml.sax.helpers.XMLReaderFactory.createXMLReader(XMLReaderFactory.java:90)
         at net.sundog.struts.ActionFinderPlugIn.parseHtmlFiles(ActionFinderPlugIn.java:76)
         at net.sundog.struts.ActionFinderPlugIn.searchDirectory(ActionFinderPlugIn.java:64)
         at net.sundog.struts.ActionFinderPlugIn.init(ActionFinderPlugIn.java:50)
         at org.apache.struts.action.ActionServlet.initModulePlugIns(ActionServlet.java:1156)
         at org.apache.struts.action.ActionServlet.init(ActionServlet.java:472)
         at javax.servlet.GenericServlet.init(GenericServlet.java:258)
         at com.evermind[Oracle9iAS (9.0.3.0.0) Containers for J2EE].server.http.HttpApplication.loadServlet(HttpApplication.java:1956)
         at com.evermind[Oracle9iAS (9.0.3.0.0) Containers for J2EE].server.http.HttpApplication.findServlet(HttpApplication.java:4355)
         at com.evermind[Oracle9iAS (9.0.3.0.0) Containers for J2EE].server.http.HttpApplication.getRequestDispatcher(HttpApplication.java:2750)
         at com.evermind[Oracle9iAS (9.0.3.0.0) Containers for J2EE].server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:617)
         at com.evermind[Oracle9iAS (9.0.3.0.0) Containers for J2EE].server.http.HttpRequestHandler.run(HttpRequestHandler.java:259)
         at com.evermind[Oracle9iAS (9.0.3.0.0) Containers for J2EE].server.http.HttpRequestHandler.run(HttpRequestHandler.java:106)
         at EDU.oswego.cs.dl.util.concurrent.PooledExecutor$Worker.run(PooledExecutor.java:803)
         at java.lang.Thread.run(Thread.java:534)

    try to look on xml.apache.org for this error. There should be some pages describing how and why setup this property.
    Basically, these properties defines factories for javax extensions. javax defines interfaces and providers than supply implementations, so for example you can use different XML parsers implementations (we use Xalan for one OC4J container and original ORACLE parser for other). To bind this together they use some defined mechanism like setting system property of including special manifest file etc. (I don't know about details)
    Myrra

  • SAX parser not finding my DTD. Help please

    I have written a small XML file and its DTD that are stored in the same folder which is C:/Work/pdftools. Here is a part of the code that is generating errors:
    inputSource.setSystemId( "c:/Work/pdftools/userSettings.xml" );
    parserAdapter.parse( inputSource );
    So, I am setting the systemID on my inputSource that I want to parse.
    But, i am encountering the following error:
    "External entity not found: "c:/Work/pdftools/userSettings.dtd"
    Does someone have any idea why is this happening?
    Thanks

    "c:/Work/pdftools/userSettings.dtd"Because that isn't a URL. Tryfile://c:/Work/pdftools/userSettings.xmlor something like that with 1 or 3 slashes after "file:".

  • Newbie help with SAX, jclark package not found

    I'm trying do a simple SAX exercise. My work files are on my d:\workspace\xml directory and I'm running win2k pro. I have extracted saxjava-1.0.zip to e:\XML\sax, the jdk to e:\j2sdk1.4.0, and james clark xp parser to e:\XML\xp
    I have set my environment variables according to the book
    variable: CLASSPATH
    value: .;E:\XML\sax;E:\XML\xp\xp.jar
    when I compile my java file I get the error:
    package com.jclark.xml.sax does not exist
    Parser parserObj = new com.jclark.xml.sax.Driver();
    Note: BandReader.java uses or overrides a deprecated API
    Note: Recompile with -deprecated for details
    1 error
    When I go into the directory E:\XML\xp\com\jclark\xml\sax , the file "Driver.java" is there
    code in my BandReader.java file
    import org.xml.sax.*;
    public class BandReader extends HandlerBase  {
         public static void main(String[] args) throws Exception  {
              System.out.println("Here we go...");
              BandReader readerObj = new BandReader();
              readerObj.read();
         public void read () throws Exception  {
              Parser parserObj = new com.jclark.xml.sax.Driver();
              parserObj.setDocumentHandler (this);
              parserObj.parse ("file:///d:/workspace/xml/bands.xml");
         public void startDocument() throws SAXException  {
              System.out.println("Starting...");
         public void endDocument() throws SAXException  {
              System.out.println("...Finished");
         public void startElement(String name, AttributeList atts) throws SAXException  {
              System.out.println("Element is " + name);
    }

    I downloaded sun's java_xml_pack-summer-02_01 and extracted the contents to e:\xml\sun and have changed my classpath environment variable to E:\XML\sun\jaxp-1.2_01:e:\XML\xp\xp.jar
    How would I change my code for my exercise to work? I tried the following and I get 4 errors.
    import java.io.*;
    import org.xml.sax.*;
    import org.xml.sax.helpers.DefaultHandler;
    import javax.xml.parsers.SAXParserFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParser;
    public class BandReader extends ContentHandler  {
         public static void main(String[] args) throws Exception  {
              System.out.println("Here we go...");
              //BandReader readerObj = new BandReader();
              //readerObj.read();
              //Use an instance of ourselves as the SAX event handler
                 DefaultHandler handler = new BandReader();
              //Use the default (non-validating) parser
                 SAXParserFactory factory = SAXParserFactory.newInstance();
         public void read () throws Exception  {
              //Parse the input
                 SAXParser parserObj = factory.newSAXParser();
              parserObj.setDocumentHandler (this);
              //Parser parserObj = new com.jclark.xml.sax.Driver();
              //parserObj.setDocumentHandler (this);
              parserObj.parse ("file:///d:/workspace/xml/bands.xml");
         public void startDocument() throws SAXException  {
              System.out.println("Starting...");
         public void endDocument() throws SAXException  {
              System.out.println("...Finished");
         public void startElement(String name, AttributeList atts) throws SAXException  {
              System.out.println("Element is " + name);
    }

  • How to create new XML file using retreived XML content by using SAX API?

    hi all,
    * How to create new XML file using retreived XML content by using SAX ?
    * I have tried my level best, but output is coming invalid format, my code is follows,
    XMLFileParser.java class :-
    import java.io.StringReader;
    import java.io.StringWriter;
    import javax.xml.transform.OutputKeys;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerConfigurationException;
    import javax.xml.transform.TransformerException;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMResult;
    import javax.xml.transform.sax.SAXSource;
    import javax.xml.transform.sax.SAXTransformerFactory;
    import javax.xml.transform.sax.TransformerHandler;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import org.xml.sax.Attributes;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.XMLFilterImpl;
    public class PdfParser extends XMLFilterImpl {
        private TransformerHandler handler;
        Document meta_data;
        private StringWriter meta_data_text = new StringWriter();
        public void startDocument() throws SAXException {
        void startValidation() throws SAXException {
            StreamResult streamResult = new StreamResult(meta_data_text);
            SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
            try
                handler = factory.newTransformerHandler();
                Transformer transformer = handler.getTransformer();
                transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                handler.setResult(streamResult);
                handler.startDocument();
            catch (TransformerConfigurationException tce)
                System.out.println("Error during the parse :"+ tce.getMessageAndLocation());
            super.startDocument();
        public void startElement(String namespaceURI, String localName,
                String qualifiedName, Attributes atts) throws SAXException {
            handler.startElement(namespaceURI, localName, qualifiedName, atts);
            super.startElement(namespaceURI, localName, qualifiedName, atts);
        public void characters(char[] text, int start, int length)
                throws SAXException {
            handler.characters(text, start, length);
            super.characters(text, start, length);
        public void endElement(String namespaceURI, String localName,
                String qualifiedName) throws SAXException {
            super.endElement("", localName, qualifiedName);
            handler.endElement("", localName, qualifiedName);
        public void endDocument() throws SAXException {
        void endValidation() throws SAXException {
            handler.endDocument();
            try {
                TransformerFactory transfactory = TransformerFactory.newInstance();
                Transformer trans = transfactory.newTransformer();
                SAXSource sax_source = new SAXSource(new InputSource(new StringReader(meta_data_text.toString())));
                DOMResult dom_result = new DOMResult();
                trans.transform(sax_source, dom_result);
                meta_data = (Document) dom_result.getNode();
                System.out.println(meta_data_text);
            catch (TransformerConfigurationException tce) {
                System.out.println("Error occurs during the parse :"+ tce.getMessageAndLocation());
            catch (TransformerException te) {
                System.out.println("Error in result transformation :"+ te.getMessageAndLocation());
    } CreateXMLFile.java class :-
    Sax.startDocument();
    Sax.startValidation();
    Sax.startElement("", "pdf", "pdf", new AttributesImpl());
    Sax.startElement("", "basic-metadata", "basic-metadata", new AttributesImpl());          
    String xmp_str = new String(meta_data.getByteArray(),"UTF8");
    char[] xmp_arr = xmp_str.toCharArray();
    Sax.characters(xmp_arr, 0, xmp_arr.length);
    Sax.endElement("", "pdf", "pdf");
    Sax.endValidation();
    Sax.endDocument();
    Sax.endElement("", "basic-metadata", "basic-metadata");* In CreateXMLFile.java
    class, I have retreived the xml content in the meta_data object, after that i have converted into character array and this will be sends to SAX
    * In this case , the XML file created successfully but the retreived XML content added as an text in between basic-metadata Element, that is, retreived XML content
    is not an XML type text, it just an Normal text Why that ?
    * Please help me what is the problem in my code?
    Cheers,
    JavaImran

    Sax.startDocument();
    Sax.startValidation();
    Sax.startElement("", "pdf", "pdf", new AttributesImpl());
    Sax.startElement("", "basic-metadata", "basic-metadata", new AttributesImpl());          
    String xmp_str = new String(meta_data.getByteArray(),"UTF8");
    char[] xmp_arr = xmp_str.toCharArray();
    Sax.characters(xmp_arr, 0, xmp_arr.length);
    </code><code>Sax.endElement("", "basic-metadata", "basic-metadata");</code>
    <code class="jive-code jive-java">Sax.endElement("", "pdf", "pdf");
    Sax.endValidation();
    Sax.endDocument();     
    * I HAVE CHANGED MY AS PER YOUR SUGGESTION, NOW SAME RESULT HAS COMING.
    * I AM NOT ABLE TO GET THE EXACT OUTPUT.,WHY THAT ?
    Thanks,
    JavaImran{code}

  • Is it possible to play my guitar and have the sound changed to different instrument like a sax? Like an emulator.

    Is it possible to play my guitar and have the sound changed to different instrument like a sax? Have my Mac act as an emulator. I'm a guitar player, not a sax player, but I want a sax solo in my song. 

    You'd need a midi guitar for that. GarageBand does not create midi from audio. Use a different application, like Finale to create a midi file from your Guitar audio file.
    Or play the sax track using a midi keyboard or simply GarageBand's musical typing. You can use the track editor to add expression and articulation afterwards.

  • Edit an XML file with SAX

    Dear all, I am so confused�.
    I have been trying for the last few days to understand how sax works� The only thing I understood is:
    DefaultHandler handler = new Echo01();
    SAXParserFactory factory = SAXParserFactory.newInstance();
            try {
                out = new OutputStreamWriter(System.out, "UTF8");
                SAXParser saxParser = factory.newSAXParser();
                saxParser.parse(file , handler);
            } catch (Throwable t) {
                t.printStackTrace();
            System.exit(0);
        }Ok, I assign the SAXParser the xml file and a handler. The parser parses and throws events that the handler catches. By implementing some handler interface or overriding the methods of an existing handler (e.g DeafultHandler class) I get to do stuff�
    But still, suppose I have implement startElement() method of DefaultHandler class and I know that the pointer is currently placed on an element e.g. <name>bob</name>. How do I get the value of the element, and if I manage to do that, how can I replace�bob� with �tom�?
    I would really appreciate any help given� just don�t recommend http://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/ because although there are interesting staff in there, it does not solve my problem�

    Maybe SAX is not the right tool for you.
    With SAX, you implement methods like startElement and characters that get called as XML data is encountered by the parser. If you want to catch it or not, the SAX parser does not care. In your case, the "bob" part will be passed in one or more calls to characters. To safely process the data, you need to do something like build a StringBuffer or StringBuilder in the constructor of the class, and then in the startElement, if the name is one you want to read, set the length to zero. In the characters method, append the data to the StringBuilder or StringBuffer. In the endElement, do a toString to keep the data wherever you want.
    This works for simple XML, but may need to be enhanced if you have nested elements with string values that contain other elements.
    On the other hand, if your file is not huge, you could use DOM. With DOM, (or with JDOM, and I would expect with Dom4J -- but I have only used the first two) you do a parse and get a Document object with the entire tree. That allows you to easily (at least it is easy once you figure out how to do it) find a node like the "name" element and change the Text object that is its child from a value of "bob" to "tom". With DOM, you can then serialize the modified Document tree and save it as an XML file. SAX does not have any way to save your data. That burden falls to you entirely.
    Dave Patterson

  • Import org.xml.sax is deprecated

    Hi All, Please help ... I am a beginner of using SAX with Java. I think I don't have the org.xml.sax.* classes in my java class. So, I downloaded "saxjava-1.0" from www.megginson.com (I hope I downloaded the correct one). I unzipped the file and put it in my Java folder. However, it doesn't work when I run my Java code. I think I might missed out something ... like didn't import the file to Java classes? If so, how can I do that? My java code is trying to read an XML file and print out how many books in the xml file. After compiled, it has the following message:
    "package com.jclark.xml.sax does not exists"
    and 2 compiler warnings:
    C:\XML\BookCounter.java:12:warning:org.xml.sax.HandlerBase in org.xml.sax has been deprecated.
    C:\XML\BookCounter.java:21:warning:org.xml.sax.Parser in org.xml.sax has been deprecated.
    My java code as follow:
    import org.xml.sax.*;
    public class BookCounter extends HandlerBase
    public static void main (String args[]) throws Exception
    (new BookCounter()).countBooks();
    public void countBooks() throws Exception
    Parser p = new com.jclark.xml.sax.Driver();
    p.setDocumentHandler(this);
    p.parse("file:///C:/books.xml");

    the error message "package com.jclark.xml.sax does not exists" has nothign to do with the post you coded, as it imports "org.xml.sax.*" and not "com.jclark.xml.sax.*".
    download sax from here: http://sourceforge.net/project/showfiles.php?group_id=29449 (sax2r2.jar), add it to your classpath and read the following how to use it:
    http://java.sun.com/webservices/docs/ea2/tutorial/doc/JAXPSAX3.html#64190

  • Jaxp underlying sax class question

    Below is a class that uses the JAXP layer and parses a xml document. All works fine and my results are proper. I would like to use the JAXP abstraction in some code at work, but I am not sure of two things.
    1) What underlying parser does this use.? I believe the answser has to do with where the class was downloaded? Crimson from sun, Xerces from Apache. But I am writing code that will go to a remote server.
    2) So if the above is true, how can I through code find out what underlying parser it is using, and can I override it somehow on this remote server?
    Thanks,
    Scott
    from java and xml oreilly
    package javaxml2;
    import java.io.File;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.io.Writer;
    // JAXP
    import javax.xml.parsers.FactoryConfigurationError;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParserFactory;
    import javax.xml.parsers.SAXParser;
    // SAX
    import org.xml.sax.AttributeList;
    import org.xml.sax.HandlerBase;
    import org.xml.sax.SAXException;
    * <p>
    * <code>TestSAXParsing</code> is a simple class that demonstrates
    * how JAXP can be used to work with SAX (the Simple API for XML).
    * </p>
    public class TestSAXParsing {
    * <p>Provide a static entry point.</p>
    public static void main(String[] args) {
    try {
    if (args.length != 1) {
    System.err.println ("Usage: java TestSAXParsing [filename]");
    System.exit (1);
    // Get SAX Parser Factory
    SAXParserFactory factory = SAXParserFactory.newInstance();
    // Turn on validation, and turn off namespaces
    factory.setValidating(true);
    factory.setNamespaceAware(false);
    SAXParser parser = factory.newSAXParser();
    parser.parse(new File(args[0]), new MyHandler());
    } catch (ParserConfigurationException e) {
    System.out.println("The underlying parser does not support the requested features.");
    } catch (FactoryConfigurationError e) {
    System.out.println("Error occurred obtaining SAX Parser Factory.");
    } catch (Exception e) {
    e.printStackTrace();
    class MyHandler extends HandlerBase {
    private Writer out;
    public MyHandler() throws SAXException {
    try {
    out = new OutputStreamWriter(System.out, "UTF8");
    } catch (IOException e) {
    throw new SAXException("Error getting output handle.", e);
    public void startDocument() throws SAXException {
    print("<?xml version=\"1.0\"?>\n");
    public void startElement(String elementName, AttributeList atts)
    throws SAXException {
    print("<" + elementName);
    if (atts != null) {
    for (int i=0, len = atts.getLength(); i<len; i++) {
    print(" " + atts.getName(i) +
    "=\"" + atts.getValue(i) + "\"");
    print(">");
    public void endElement(String elementName) throws SAXException {
    print("</" + elementName + ">\n");
    public void characters(char[] ch, int start, int len) throws SAXException {
    print(new String(ch, start, len));
    private void print(String s) throws SAXException {
    try {
    out.write(s);
    out.flush();
    } catch (IOException e) {
    throw new SAXException("IO Error Occurred.", e);

    I see that there are a number of code snippets on that page, for clarity I meant this one in particular. It checks for just about every parser known before calling default. Sorry for confusion. You wouldn't have to check for this many parsers, but I sometimes take Xerces if it is there over the default.
      XMLReader parser;
      try { // Xerces
        parser = XMLReaderFactory.createXMLReader(
         "org.apache.xerces.parsers.SAXParser"
      catch (SAXException e1) {
        try { // Crimson
          parser = XMLReaderFactory.createXMLReader(
           "org.apache.crimson.parser.XMLReaderImpl"
        catch (SAXException e2) {
          try { // ?lfred
            parser = XMLReaderFactory.createXMLReader(
             "gnu.xml.aelfred2.XmlReader"
          catch (SAXException e3) {
            try { // Piccolo
              parser = XMLReaderFactory.createXMLReader(
                "com.bluecast.xml.Piccolo"
            catch (SAXException e4) {
              try { // Oracle
                parser = XMLReaderFactory.createXMLReader(
                  "oracle.xml.parser.v2.SAXParser"
              catch (SAXException e5) {
                try { // default
                  parser = XMLReaderFactory.createXMLReader();
                catch (SAXException e6) {
                  throw new NoClassDefFoundError(
                    "No SAX parser is available");
                    // or whatever exception your method is 
                    // declared to throw
      }

  • Inavlid SAX transformation

    Hi,
    I am getting this error when i try to open the first page of my application
    here tack trace:-
    006-06-21 22:10:00,609 [DaemonThread:feeddaemon] ERROR SimpleTransform - Invalid SAX Transformer:
    org.xml.sax.SAXException: Can not resolve namespace prefix: aocs
         at org.apache.xalan.processor.XSLTAttributeDef.processPREFIX_LIST(XSLTAttributeDef.java:1281)
         at org.apache.xalan.processor.XSLTAttributeDef.processValue(XSLTAttributeDef.java:1451)
         at org.apache.xalan.processor.XSLTAttributeDef.setAttrValue(XSLTAttributeDef.java:1600)
         at org.apache.xalan.processor.XSLTElementProcessor.setPropertiesFromAttributes(XSLTElementProcessor.java:342)
         at org.apache.xalan.processor.XSLTElementProcessor.setPropertiesFromAttributes(XSLTElementProcessor.java:267)
         at org.apache.xalan.processor.ProcessorStylesheetElement.startElement(ProcessorStylesheetElement.java:101)
         at org.apache.xalan.processor.StylesheetHandler.startElement(StylesheetHandler.java:600)
         at org.apache.xerces.parsers.AbstractSAXParser.startElement(Unknown Source)
         at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
         at org.apache.xerces.impl.XMLNSDocumentScannerImpl$NSContentDispatcher.scanRootElementHook(Unknown Source)
         at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
         at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
         at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
         at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
         at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
         at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
         at org.apache.jetspeed.util.SimpleTransform.SAXTransform(SimpleTransform.java:442)
         at org.apache.jetspeed.daemon.impl.FeedDaemon.getEntries(FeedDaemon.java:255)
         at org.apache.jetspeed.daemon.impl.FeedDaemon.run(FeedDaemon.java:195)
         at org.apache.jetspeed.daemon.DaemonThread.runDaemon(DaemonThread.java:147)
         at org.apache.jetspeed.daemon.DaemonThread.run(DaemonThread.java:131)
    2006-06-21 22:10:00,609 [DaemonThread:feeddaemon] ERROR FeedDaemon - FeedDaemon: Couldn't process URL: http://jakarta.apache.org/jetspeed/channels/apache.ocs
    java.io.IOException: problem in SAX transform: org.xml.sax.SAXException: Can not resolve namespace prefix: aocs
         at org.apache.jetspeed.util.SimpleTransform.SAXTransform(SimpleTransform.java:524)
         at org.apache.jetspeed.daemon.impl.FeedDaemon.getEntries(FeedDaemon.java:255)
         at org.apache.jetspeed.daemon.impl.FeedDaemon.run(FeedDaemon.java:195)
         at org.apache.jetspeed.daemon.DaemonThread.runDaemon(DaemonThread.java:147)
         at org.apache.jetspeed.daemon.DaemonThread.run(DaemonThread.java:131)
    Can any body help me in solving this error

    It seems like will work on PI 7.31 systems.
    com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl
         factoryParser = new com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl();

Maybe you are looking for