SAX Parser quick question

When you are parsing a file using the Sax do you have to set validation method on both the factory and the parse for it validate that the file is well formed XML?
saxParserFactory.isValidating(true);
saxParser.isValidating(true);
Thanks

no. setting it on the factory will create parsers with that setting already set to true.

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

  • Question on SAX Parser: retrieving child

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

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

  • Question on SAX Parsing?

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

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

  • 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

  • How to deal with empty tags in a SAX Parser

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

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

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

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

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

  • SAX Parser

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

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

  • Using the SAX Parser

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

    Repost

  • JDBC receiver adapter - Error processing request in sax parser

    Hello,
    I want to INSERT idoc data via JDBC adapter into a MS SQL database. After digging through SAP Help, numerous blogs and forum discussions on SDN and even posting an OSS message I still get the same error:
    'Error: TransformException error in xml processor class: Error processing request in sax parser: No 'action' attribute found in XML document (attribute "action" missing or wrong XML structure)'
    When testing my mapping in the Integration Repository the resulting XML message is:
    <?xml version="1.0" encoding="UTF-8"?>
    <ns0:Employee xmlns:ns0="http://prodrive.nl/xi/HRMasterdata/HRMD_A_2_d_bcommerp">
       <STATEMENT>
          <T_PD_Employees action="INSERT">
             <access>
                <KeyTag>00088888</KeyTag>
                <PerNo>00088888</PerNo>
             </access>
          </T_PD_Employees>
       </STATEMENT>
    </ns0:Employee>
    The connection to the database is fine, Sender adapter with a SELECT * works perfect.
    Can anyone help me solve this problem? I'm lost.
    Best regards,
    Roelof Jan Bouwknegt

    Hi Bhavesh,
    I have tried out the change you suggested. Without success. Message I get back is
    - 2006-12-28 10:34:08 CET: Error: TransformException error in xml processor class: Error processing request in sax parser: No 'action' attribute found in XML document (attribute "action" missing or wrong XML structure)
    structure in testtool:
    <?xml version="1.0" encoding="UTF-8"?>
    <ns0:Employee xmlns:ns0="http://prodrive.nl/xi/HRMasterdata/HRMD_A_2_d_bcommerp">
       <STATEMENT>
          <T_PD_Employees action="INSERT">
             <ACCESS>
                <KEYTAG>00088888</KEYTAG>
                <PERNO>00088888</PERNO>
             </ACCESS>
          </T_PD_Employees>
       </STATEMENT>
    </ns0:Employee>
    Somehow the SAX  parser doesn't like the result of my mapping. Maybe there is something wrong with the structure cardinality. Let me describe what I have built:
    XSD:
    WA_T_PD_Employees - Complex Type
    > STATEMENT - Element - Occurence = 1
    >> T_PD_Employees - Element - Occurence = 1
    >>> STATEMENT - Attribute - Occurence = optional
    >>> access - Element - Occurence = 1..Unbounded
    Best regards Roelof Jan and thanks for your quick response

  • How to get a specific tag value from SAX parser

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

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

  • SAX parser splits up character data; I expected Ign. whitesp

    Im am working on a XML parser for loading data from some back
    end systems into an Oracle 8i database. I am using the SAX
    parser for this purpose. After doing some tests with larger
    amounts of XML data (> 1M), I found some unexpected behaviour.
    The parser sometimes splits up character data into two chunks of
    data. The XML looks as follows:
    <TAGNAME> this is the character data </TAGNAME>
    The parser raises the following events:
    1 startElement name = "TAGNAME"
    2 characters chbuf = " "
    3 characters chbuf = "this is the character data "
    4 endElement name = "TAGNAME"
    I expected an ignorableWhitespace event at step 2. The XML
    document contains repetitive tagnames. The strange thing about
    the parse process is that the parser splits up the character
    data only sometimes, and I can't determine any kind of logica
    for this behaviour. Most occurrences of exactly the same tagname
    and character data are parsed correctly (that is, as I
    expected).
    Am I dealing with correct behaviour here, or is it a bug??
    Rolf.
    null

    Oracle XML Team wrote:
    : Rolf van Deursen (guest) wrote:
    : : Im am working on a XML parser for loading data from some
    back
    : : end systems into an Oracle 8i database. I am using the SAX
    : : parser for this purpose. After doing some tests with larger
    : : amounts of XML data (> 1M), I found some unexpected
    behaviour.
    : : The parser sometimes splits up character data into two
    chunks
    : of
    : : data. The XML looks as follows:
    : : <TAGNAME> this is the character data </TAGNAME>
    : : The parser raises the following events:
    : : 1 startElement name = "TAGNAME"
    : : 2 characters chbuf = " "
    : : 3 characters chbuf = "this is the character data "
    : : 4 endElement name = "TAGNAME"
    : : I expected an ignorableWhitespace event at step 2. The XML
    : : document contains repetitive tagnames. The strange thing
    about
    : : the parse process is that the parser splits up the character
    : : data only sometimes, and I can't determine any kind of
    logica
    : : for this behaviour. Most occurrences of exactly the same
    : tagname
    : : and character data are parsed correctly (that is, as I
    : : expected).
    : : Am I dealing with correct behaviour here, or is it a bug??
    : : Rolf.
    : The behavior is expected and correct. Could you elaborate on
    why
    : you would expect the parser to treat the whitespace signalled
    in
    : step 2 as ignorable?
    : Oracle XML Team
    : http://technet.oracle.com
    : Oracle Technology Network
    Thank you for your quick response.
    In my test XML, there are about 27500 tags containing character
    data. All character data starts with a whitespace character.
    After parsing the xml, the whitespace of only 5 (!) tags is
    treated as a seperate character event (so two character events
    are raised in succession). The remaining tags all raise only ONE
    character event for the entire character data. I can't explain
    the difference in treatment.
    null

  • Sax parser support

    hi,
    i want to kow from which version jdk release sax parser is being supported.
    regards
    ac

    XML APIs were added in Java 1.4.You could have saved you the time by checking the other threads. The question had already been answered, and that's why I just hate cross-posters.
    /Kaj

Maybe you are looking for