SAX parser getValue() method

All,
Whever i get the attribute value using getValue() method , it returns me the result with the lower case string
for example if i have something like this
<input label="Last Name:" />
and i try to get the attribute value of label
String label = attrs.getValue("label");
The result will be
label = "last name"
It doesnot adhere with the case (it returns the value by converting it into lower case)
Is it something that i am doing wrong , or its the way SAX parser internally does it.
I am using the SAX parser which comes with the BlackBerry JDE.
Any answers , pointers will be helpful

Never mind , my input to the SAX parser itself is somehow getting all lower case.
Thanks!

Similar Messages

  • SAX Parser method charaters trouble

    Hi,
    I am using a sax parser for loading an xml file of size over 1gb. The problem whats happening is that the content gets truncated at random.
    And this truncation happens in the characters method of the sax parser. This am sure as I logged the content I get from characters method before starting my processing. for ex:
    <content>signal1,signal960</content>
    <content>signal1,signal970</content>
    On parsing the above snippet, the first content "signal1,signal960"
    gets extracted completely, however the next one is truncated, and the truncation is random. This happens for some tags, and then the extraction resumes normally. And this truncation starts occuring again after it has extracted a few tags.
    Also the first truncation started occuring only after parsing around 200 mb of the 1gb file.
    Could anyone tell if there is some limitation with XERCES or CRIMSON.
    or if any other one that I can use???
    Regards,
    R.

    To quote from the Documentation of ContentHandler.characters:
    -- start quote --
    The Parser will call this method to report each chunk of character data. SAX parsers may return all contiguous character data in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity so that the Locator provides useful information.
    -- end quote --
    So providing the content in two seperate calls is perfectly valid and must be handled by your code. It's probably a result of the internal workings of the XML parser and allowing that in the Parser specification probably allowed some optimizations that would otherwise be impossible (a constant buffer size, for example).

  • Characters method in SAX parser

    Hi
    I have a SAX Parser Appln where in I am trying to run it in English Locale But the xml file contains Arabic Characters.
    The method characters looks like this
    public void characters(char buf[], int offset, int len) throws SAXException
    if (recognisedTopElementStarted && storyStarted && recognisedElementStarted )
    buffer.append ( new String(buf,offset,len) ) ;
    //buffer.append ( new String(buf,offset,len,"UTF-16") ) ;
    In this method I want to convert the char array to byte array so as to specify the encoding for constructing a String object(Arabic characters) with correct encoding as specified in the commented statement.
    How to do it so as to get the arabic characters
    Thanks
    Raj

    Hi Raj,
    I don't have Arabic support on my machine, so I tried with Greek, which has a significant Unicode code page.
    To get a byte array, I did this:
    byte[] ba = new String(buf, offset, len).getBytes("utf-16");To double check, I saved the byte array in a file output stream and validated the encoding in XML Spy.
    So it works for Greek, let's hope it will work for our friends across the Mediterranean sea ;-)
    Regards,
    David

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

  • Sax parser problem

    hi,
    i am assuming the problem is with sax parser but i cant be sure. I am parsing a xml file (about 1.4MB) with some data in it. the parser i have created reads the xml file correctly for the most part but when at some point the
    "public void characters(char buf[], int offset, int len) throws SAXException"
    function stops working correctly....i.e it doesnt fully read read the data between the "<start>" and "</start>" element. say it reads about 100 id's correctly---for 101 ID it does this. This is just an example. Since, the problem might be with how :
    "public void characters(char buf[], int offset, int len) throws SAXException"
    function is reading the data i was wondering if anybody else had encountered this problem or please let me know if i need to change something in the code: here's a part of the code :
    Bascially i have created three classes to enter data into three mysql tables and as i parse the data i fill up the columns by matching the column header with the tagName.
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.*;
    import java.io.*;
    import java.util.ArrayList;
    import java.lang.Object;
    import org.xml.sax.*;
    import org.xml.sax.helpers.DefaultHandler;
    import java.util.*;
    import javax.xml.parsers.SAXParserFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParser;
    public class Echo03 extends DefaultHandler
    StringBuffer textBuffer;
    int issuedValue, prodValue;
    OrdHeader header = new OrdHeader();
    OrdDetail detail = new OrdDetail();
    Member memInfo = new Member();
    //new addition to store the dynamic value of the products
    TestOrdheader prod = new TestOrdheader();
    int counter;
    String tag, newTag;
    SetValue setVal = new SetValue();
    String test;
    public static void main(String argv[])
    if (argv.length != 1) {
    System.err.println("Usage: cmd filename");
    System.exit(1);
    // Use an instance of ourselves as the SAX event handler
    DefaultHandler handler = new Echo03();
    // Use the default (non-validating) parser
    SAXParserFactory factory = SAXParserFactory.newInstance();
    try {
    // Set up output stream
    out = new OutputStreamWriter(System.out, "UTF8");
    // Parse the input
    SAXParser saxParser = factory.newSAXParser();
    saxParser.parse( new File(argv[0]), handler);
    } catch (Throwable t) {
    t.printStackTrace();
    System.exit(0);
    static private Writer out;
    private String indentString = " "; // Amount to indent
    private int indentLevel = 0;
    //===========================================================
    // SAX DocumentHandler methods
    //===========================================================
    public void startDocument()
    throws SAXException
    nl();
    nl();
    emit("START DOCUMENT");
    nl();
    emit("<?xml version='1.0' encoding='UTF-8'?>");
    header.assign();
    public void endDocument()
    throws SAXException
    nl(); emit("END DOCUMENT");
    try {
    nl();
    out.flush();
    } catch (IOException e) {
    throw new SAXException("I/O error", e);
    public void startElement(String namespaceURI,
    String lName, // local name
    String qName, // qualified name
    Attributes attrs)
    throws SAXException
    indentLevel++;
    nl(); //emit("ELEMENT: ");
    String eName = lName; // element name
    if ("".equals(eName)) eName = qName; // namespaceAware = false
    if (qName.equals("Billing")){
    issuedValue = 1;
    }else if (qName.equals("Shipping")){
    issuedValue = 2;
    }else if (qName.equals("ShippingTotal")){
    issuedValue = 3;
    //check to see if "Product" is the name of the element thats coming next
    if (qName.equals("Product")){
    if (issuedValue != 3){
    prodValue = 1;
    prod.addCounter();
    }else{
    prodValue = 0;
    tag = eName;
    if (attrs != null) {
    for (int i = 0; i < attrs.getLength(); i++) {
    String aName = attrs.getLocalName(i); // Attr name
    if ("".equals(aName)) aName = attrs.getQName(i);
    nl();
    emit(" ATTR: ");
    emit(aName);
    emit("\t\"");
    emit(attrs.getValue(i));
    emit("\"");
    if (attrs.getLength() > 0) nl();
    public void endElement(String namespaceURI,
    String sName, // simple name
    String qName // qualified name
    throws SAXException
    nl();
    String eName = sName; // element name
    if ("".equals(eName)){
    eName = qName; // not namespaceAware
    if ("Order".equals(eName)){          
    //enter into database
         databaseEnter();
    textBuffer = null;
    indentLevel--;
    public void characters(char buf[], int offset, int len)
    throws SAXException
    nl();
    try {
    String s = new String(buf, offset, len);
    if (!s.trim().equals("")){
    settag(tag, s);
    s = null;
    }catch (NullPointerException E){
    System.out.println("Null pointer Exception:"+E);
    //===========================================================
    // Utility Methods ...
    //===========================================================
    // Wrap I/O exceptions in SAX exceptions, to
    // suit handler signature requirements
    private void emit(String s)
    throws SAXException
    try {
    out.write(s);
    out.flush();
    } catch (IOException e) {
    throw new SAXException("I/O error", e);
    // Start a new line
    // and indent the next line appropriately
    private void nl()
    throws SAXException
    String lineEnd = System.getProperty("line.separator");
    try {
    out.write(lineEnd);
    for (int i=0; i < indentLevel; i++) out.write(indentString);
    } catch (IOException e) {
    throw new SAXException("I/O error", e);
    ===================================================================
    ///User defined methods
    ===================================================================
    private String strsplit(String splitstr){
    String delimiter = new String("=");
    String[] value = splitstr.split(delimiter);
    value[1] = value[1].replace(':', ' ');
    return value[1];
    public void settag(String tag, String s){         
    String pp_transid = null, pp_respmsg = null,pp_authid = null, pp_avs = null, pp_avszip = null;
    if ((tag.equals("OrderDate")) || (tag.equals("OrderProcessingInfo"))){
    if (tag.equals("OrderDate")){
    StringTokenizer st = new StringTokenizer(s);
    String orddate = st.nextToken();
    String ordtime = st.nextToken();
    header.put("ordDate", orddate);
    header.put("ordTime", ordtime);
    }else if (tag.equals("OrderProcessingInfo")){
    StringTokenizer st1 = new StringTokenizer(s);
    int tokenCount = 1;
    while (tokenCount <= st1.countTokens()){
    switch(tokenCount){
    case 1:
    String extra = st1.nextToken();
    break;
    case 2:
    String Opp_transid = st1.nextToken();
    pp_transid = strsplit(Opp_transid);
    break;
    case 3:
    String Opp_respmsg = st1.nextToken();
    pp_respmsg = strsplit(Opp_respmsg);
    break;
    case 4:
    String Opp_authid = st1.nextToken();
    pp_authid = strsplit(Opp_authid);
    break;
    case 5:
    String Opp_avs = st1.nextToken();
    pp_avs = strsplit(Opp_avs);
    break;
    case 6:
    String Opp_avszip = st1.nextToken();
    pp_avszip = strsplit(Opp_avszip);
    break;
    tokenCount++;
    header.put("pp_transid", pp_transid);
    header.put("pp_respmsg", pp_respmsg);
    header.put("pp_authid", pp_authid);
    header.put("pp_avs", pp_avs);
    header.put("pp_avszip", pp_avszip);
    }else{
    newTag = new String(setVal.set_name(tag, issuedValue));
    header.put(newTag, s);
    //detail.put(newTag, s);
    prod.put(newTag, s);
    memInfo.put(newTag,s);
    //Check to see-- if we should add this product to the database or not
    boolean check = prod.checkValid(newTag, prodValue);
    if (check){
    prod.addValues(s);
    setVal.clearMod();
    ==================================================================
    Here's the error that i get:
    java.util.NoSuchElementException
    at org.apache.crimson.parser.Parser2.parseInternal(Parser2.java:691)
    at org.apache.crimson.parser.Parser2.parse(Parser2.java:337)
    at org.apache.crimson.parser.XMLReaderImpl.parse(XMLReaderImpl.java:448)
    at javax.xml.parsers.SAXParser.parse(SAXParser.java:345)
    at javax.xml.parsers.SAXParser.parse(SAXParser.java:281)
    at Echo03.main(Echo03.java:47)

    I haven't gone through your code but I also had a similar error....and the exception in my was because of an "&" instead of the entity reference & in one of the element values. I use a non-validating parser but if you use a validating one then this might not be the reason for your exception.

  • 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

  • XML to CSV using SAX Parser

    Hello
    I need to convert xml files to csv format using SAX Parser. The following code & outputs are as below:
    XML file:
    <Library>
    <Book>
         <Title>Professional JINI</Title>
         <Author>bs</Author>
         <Publisher>Oreilly Publications</Publisher>
    </Book>
    <Book>
         <Title>XML Programming</Title>
         <Author>java</Author>
         <Publisher>Mann Publications</Publisher>
    </Book>
    </Library>
    public class BooksLibrary extends DefaultHandler
    protected static final String XML_FILE_NAME = "C:\\library1.xml";
         public static void main (String argv [])
              // Use the default (non-validating) parser
              SAXParserFactory factory = SAXParserFactory.newInstance();
              try {
                   FileOutputStream fos=new FileOutputStream("C:/test.txt");
                   // Set up output stream
                   out = new OutputStreamWriter (fos, "UTF8");
                   // Parse the input
                   SAXParser saxParser = factory.newSAXParser();
                   saxParser.parse( new File(XML_FILE_NAME), new BooksLibrary() );
              } catch (Throwable t) {
                   t.printStackTrace ();
              System.exit (0);
         static private Writer out;
         //===========================================================
         // Methods in SAX DocumentHandler
         //===========================================================
         public void startDocument ()
         throws SAXException
              showData ("<?xml version='1.0' encoding='UTF-8'?>");
              newLine();
         public void endDocument ()
         throws SAXException
              try {
                   newLine();
                   out.flush ();
              } catch (IOException e) {
                   throw new SAXException ("I/O error", e);
         public void startElement (String name, Attributes attrs)
         throws SAXException
              showData ("<"+name);
              if (attrs != null) {
                   for (int i = 0; i < attrs.getLength (); i++) {
                        showData (" ");
                        showData (attrs.getLocalName(i)+"=\""+attrs.getValue (i)+"\"");
              showData (">");
         public void endElement (String name)
         throws SAXException
              showData ("</"+name+">");
         public void characters (char buf [], int offset, int len)
         throws SAXException
              String s = new String(buf, offset, len);
              showData (s);
         //===========================================================
         // Helpers Methods
         //===========================================================
         // Wrap I/O exceptions in SAX exceptions, to
         // suit handler signature requirements
         private void showData (String s)
         throws SAXException
              try {
                   out.write (s);
                   out.flush ();
              } catch (IOException e) {
                   throw new SAXException ("I/O error", e);
         // Start a new line
         private void newLine ()
         throws SAXException
              //String lineEnd = System.getProperty("line.separator");
              try {
                   out.write (", ");
              } catch (IOException e) {
                   throw new SAXException ("I/O error", e);
    --------------------------------------------------------------------------------------------------output is as follows:
    <?xml version='1.0' encoding='UTF-8'?>,
         Professional JINI
         bs
         Oreilly Publications
         XML Programming
         java
         Mann Publications
    Can anyone please tell me how to remove that indentation space & get the output as :
    <?xml version='1.0' encoding='UTF-8'?>, Professional JINI, bs, Oreilly Publications, XML Programming, java, Mann Publications
    Thanks

    By the way, there is a new feature in Java 5.0 (Tiger) called "Annotations."
    Since your code extneds DefaultHandler, you could specify a line with
    @Override
    before the definition of each of your methods. If you had used these, the compiler would have given an error since your methods did not override the methods of DefaultHandler.
    (If your code implemented ContentHandler, by contrast, using @Override is invalid because you need to implement all of the methods defined in the interface definition.)
    The other comment is that the safest way to handle characters() data is to use a StringBuilder/Buffer (StringBuilder is only valid in 5.0, StringBuffer has been around since Release 1.0) that you define in the startElement method. Use the append method to gather data presented to you in the characters() method and use toString() to harvest the data in the endElement method.
    Dave Patterson

  • Xerces SAX parser don`t initialize a characters array

    Xerces SAX parser don`t initialize a characters array from characters() method in DefaultHandler.
    I use jdk 1.5.12.
    For value "22-11-2009" variables start=1991, length=9.
    Result: "22-11-200"

    My handler:
    package com.epam.xmltask.parsers;
    import com.epam.xmltask.model.Category;
    import com.epam.xmltask.model.Goods;
    import com.epam.xmltask.model.Products;
    import com.epam.xmltask.model.Subcategory;
    import com.epam.xmltask.utils.Constants;
    import com.epam.xmltask.utils.DateConverter;
    import java.text.ParseException;
    import java.util.Date;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.Attributes;
    import org.xml.sax.ErrorHandler;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.xml.sax.helpers.DefaultHandler;
    public class SAXProductsParser extends DefaultHandler implements IProductsParser {
        private Logger logger = null;
        private SAXParser parser = null;
        private ErrorHandler errorHandler = null;
        private Products products = null;
        private Category category = null;
        private Subcategory subcategory = null;
        private Goods goods = null;
        private String currentField = Constants.EMPTY_STRING;
        protected Logger getLogger() {
            if (logger == null) {
                logger = Logger.getLogger(SAXProductsParser.class.getName());
            return logger;
        protected SAXParser getParser() throws Exception {
            if (parser == null) {
                try {
                    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
                    parserFactory.setNamespaceAware(true);
                    parserFactory.setValidating(true);
                    parser = parserFactory.newSAXParser();
                    parser.setProperty(Constants.SCHEMA_LANGUAGE, Constants.XML_SCHEMA);
                } catch (Exception ex) {
                    getLogger().log(Level.SEVERE, null, ex);
                    throw ex;
            return parser;
        public ErrorHandler getErrorHandler() {
            if (errorHandler == null) {
                errorHandler = new ProductsErrorHandler();
            return errorHandler;
        public Products getProducts(String uri) throws Exception {
            try {
                products = new Products();
                getParser().parse(uri, this);
                return products;
            } catch (Exception ex) {
                getLogger().log(Level.SEVERE, null, ex);
                throw ex;
        @Override
        public void startElement(String uri, String localName,
                String qName, Attributes attributes) {
            if (Constants.CATEGORY.equals(qName)) {
                String name = attributes.getValue(Constants.NAME);
                category = new Category(name);
            } else if (Constants.SUBCATEGORY.equals(qName)) {
                String name = attributes.getValue(Constants.NAME);
                subcategory = new Subcategory(name);
            } else if (Constants.GOODS.equals(qName)) {
                String name = attributes.getValue(Constants.NAME);
                goods = new Goods(name);
            } else if (Constants.NOT_IN_STOCK.equals(qName)) {
                goods.setIsInStock(false);
            } else {
                currentField = qName;
        @Override
        public void endElement(String uri, String localName, String qName) {
            if (Constants.CATEGORY.equals(qName)) {
                products.addCategory(category);
                category = null;
            } else if (Constants.SUBCATEGORY.equals(qName)) {
                category.addSubcategory(subcategory);
                subcategory = null;
            } else if (Constants.GOODS.equals(qName)) {
                subcategory.addGoods(goods);
                goods = null;
            } else {
                currentField = Constants.EMPTY_STRING;
        @Override
        public void characters(char[] chars, int start, int length) throws SAXException {
            String field = new String(chars, start, length).trim();
            if (goods != null) {
                if (Constants.PRODUSER.equals(currentField)) {
                    goods.setProducer(field);
                } else if (Constants.MODEL.equals(currentField)) {
                    goods.setModel(field);
                } else if (Constants.DATE_OF_ISSUE.equals(currentField)) {
                    Date date = null;
                    try {
                        date = DateConverter.getConvertedDate(field);
                    } catch (ParseException ex) {
                        getLogger().log(Level.SEVERE, null, ex);
                        throw new SAXException(ex);
                    goods.setDateOfIssue(date);
                } else if (Constants.COLOR.equals(currentField)) {
                    goods.setColor(field);
                } else if (Constants.PRICE.equals(currentField)) {
                    Float price = Float.valueOf(field);
                    goods.setPrice(price);
        @Override
        public void error(SAXParseException ex) throws SAXException {
            getErrorHandler().error(ex);
        @Override
        public void fatalError(SAXParseException ex) throws SAXException {
            getErrorHandler().fatalError(ex);
        @Override
        public void warning(SAXParseException ex) throws SAXException {
            getErrorHandler().warning(ex);
    }

  • SAX parsing and loops problem

    Hi!
    I currently have an XML file which looks like this:
    <jel>
    <admin creation="Fri Nov 09 17:14:55 GMT 2007" xsdversion="1.0.0" version="1.0.0"/>
    &#8722;
         <jelclass superclass="Object" visibility="public" package="" superclassfulltype="java.lang.Object" fulltype="Player" type="Player">
    &#8722;
         <implements>
    <interface fulltype="java.awt.event.ActionListener" type="ActionListener"/>
    <interface fulltype="java.awt.event.KeyListener" type="KeyListener"/>
    </implements>
    &#8722;
         <methods>
    &#8722;
         <constructor visibility="public" name="Player">
    &#8722;
         <params>
    <param name="newProtocol" fulltype="NewProtocol" type="NewProtocol"/>
    <param name="x" fulltype="int" type="int"/>
    <param name="y" fulltype="int" type="int"/>
    </params>
    </constructor>
    &#8722;
         <method visibility="public" name="actionPerformed" fulltype="void" type="void">
    &#8722;
         <params>
    <param name="e" fulltype="java.awt.event.ActionEvent" type="ActionEvent"/>
    </params>
    </method>
    &#8722;
         <method visibility="public" name="keyPressed" fulltype="void" type="void">
    &#8722;
         <params>
    <param name="e" fulltype="java.awt.event.KeyEvent" type="KeyEvent"/>
    </params>
    </method>
    &#8722;
         <method visibility="public" name="keyReleased" fulltype="void" type="void">
    &#8722;
         <params>
    <param name="e" fulltype="java.awt.event.KeyEvent" type="KeyEvent"/>
    </params>
    </method>
    &#8722;
         <method visibility="public" name="keyTyped" fulltype="void" type="void">
    &#8722;
         <params>
    <param name="e" fulltype="java.awt.event.KeyEvent" type="KeyEvent"/>
    </params>
    </method>
    <method visibility="public" name="getX" fulltype="int" type="int"/>
    &#8722;
         <method visibility="public" name="setX" fulltype="void" type="void">
    &#8722;
         <params>
    <param name="x" fulltype="int" type="int"/>
    </params>
    </method>
    <method visibility="public" name="getY" fulltype="int" type="int"/>
    &#8722;
         <method visibility="public" name="setY" fulltype="void" type="void">
    &#8722;
         <params>
    <param name="y" fulltype="int" type="int"/>
    </params>
    </method>
    </methods>
    </jelclass>And I have SAX parsing code that looks like this:
    public class SaxParser{
          private HashSet <String>packageSet = new HashSet<String>();
          private ArrayList <String> classList = new ArrayList<String>();
          private ArrayList <String> packageList = new ArrayList<String>();
          private ArrayList <String> methodList = new ArrayList<String>();
          private Object[] packageNames;
          private HashMap <String, ArrayList> h = new HashMap <String, ArrayList>();
          public SaxParser()throws Exception{
              String fname = "eclipse/jel.xml";
             DefaultHandler handler = new DefaultHandler()
                 private int numberOfClasses = 0;
             public void startElement(String namespaceURI,String localName, String qname, Attributes attrs)
                  if(qname.equals("jelclass")) {
                       numberOfClasses ++;
                  for(int i = 0; i< attrs.getLength();i++){
                        if(attrs.getQName(i).equals("type")){
                             classList.add(attrs.getValue(i));
                             if(attrs.getQName(i).equals("package")){
                                  packageList.add(attrs.getValue(i));
                                  packageSet.add(attrs.getValue(i));
                  for(int i = 0; i< attrs.getLength();i++){
                       for(int j = 0; j < classList.size(); j++){
              if(attrs.getQName(i).equals("type") && attrs.getValue(i).equals(classList.get(j))){
                  if(qname.equals("method")){
                        if(attrs.getQName(i).equals("name")){
                                    h.put(classList.get(i), methodList.add(attrs.getValue(i));
                   packageNames = new String[packageSet.size()];
                  packageNames = packageSet.toArray();
             public void endElement(String namespaceURI,String localName, String qname){}};
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();
            saxParser.parse(new File(fname), handler);
         public int getPackageNumber(){
              return packageSet.size();
         public Object[] getPackageNames(){
              return packageNames;
         public ArrayList getPackageList(){
              return packageList;
         public ArrayList getClassList(){
              return classList;
         public ArrayList getMethodList(){
              return methodList;
          public static void main(String[] args)throws Exception{
               new SaxParser();
    }I am currently pulling out the package names, pulling out the classnames and then mapping these in a separate class - this works because the class and package names are declared in the same line, so if a package name appears in the package list 7 times, i know this package has 7 classes, and therefore i count the first 7 classes out of an array of all the classes and know that these are the right 7 for that package. However, the methods are a bit different:
    What I would like to do is to: for every class make a hashmap which maps the class name onto an arraylist of the methods, but i think i'm getting confused with my for loops. Or even just keep a tally of how many methods each class has, then I can work it out as i did with the packages -> classes.
    Does anyone know where im going wrong, or have any ideas at all?
    Thank you for your time,
    beccy
    :)

    I don't know if stacks are specifically mentioned in any SAX documentation.
    Basically, SAX sends you a stream of XML elements (open and close tags, characters, etc.), but it doesn't know anything about the underlying XML structure. You have to add that part (usually -- sometimes when writing a SAX application, you don't really care about the XML structure). XML structure is a tree.
    If you've ever written a recursive function that spans a tree, you'll have an idea what to do. You can use a stack to keep track of where you are in the tree. For example, if you open tag A, then you're "in" the A element for subsequent content in that document; if you then open tag B, you're in the B element; but when you close the B tag, you need the stack to tell you that now you're back in the A element.
    You may not need stacks, but it's likely. Find a good tutorial about SAX that mentions stacks and you'll be fine.
    Edited by: paulcw on Nov 14, 2007 4:09 PM

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

  • Is there a SAX parser with PL/SQL??

    Hi All,
    I am a Oracle developer and generally want to do everything from PL/SQL.
    So, from a PL/SQL procedure I would like to parse a XML document. I have tried hard to find a PL/SQL package which can give me a PL/SQL SAX parser, but could not find one.
    All packages are based on DOM tree.
    Please convey if I am wrong and is there a SAX parser?
    I know that there is only one package DBMS_XMLSTORE which is C based and uses SAX parser, but it does not have procedures/functions like ".parse()".
    Thanks and regards

    Here's an example
    SQL> --
    SQL> define MODULE=SaxProcessor
    SQL> define CLASS=com/oracle/st/xmldb/pm/examples/SaxProcessor
    SQL> --
    SQL> set define off
    SQL> --
    SQL> var sourceFileName varchar2(32)
    SQL> var targetPath varchar2(1024)
    SQL> --
    SQL> begin
      2    :sourceFileName := 'JavaSource';
      3    :targetPath  := '/public/' || :sourceFileName || '.java';
      4  end;
      5  /
    PL/SQL procedure successfully completed.
    SQL> declare
      2    res boolean;
      3    javaSource clob :=
      4  'package com.oracle.st.xmldb.pm.examples;
      5
      6
      7  import java.io.IOException;
      8  import java.io.StringWriter;
      9
    10  import java.io.Writer;
    11
    12  import java.sql.DriverManager;
    13  import java.sql.SQLException;
    14
    15  import java.util.Enumeration;
    16  import java.util.Hashtable;
    17
    18  import oracle.jdbc.OracleConnection;
    19  import oracle.jdbc.OracleDriver;
    20
    21  import oracle.jdbc.OraclePreparedStatement;
    22
    23  import oracle.sql.BFILE;
    24
    25  import oracle.sql.CLOB;
    26
    27  import oracle.xml.parser.v2.SAXParser;
    28  import oracle.xml.parser.v2.XMLDocument;
    29  import oracle.xml.parser.v2.XMLElement;
    30
    31
    32  import org.w3c.dom.Attr;
    33  import org.w3c.dom.Element;
    34  import org.w3c.dom.Node;
    35
    36  import org.xml.sax.Attributes;
    37  import org.xml.sax.ContentHandler;
    38  import org.xml.sax.Locator;
    39  import org.xml.sax.SAXException;
    40
    41  public class SaxProcessor implements ContentHandler {
    42
    43      public static final boolean DEBUG = true;
    44
    45      private OracleConnection dbConnection;
    46
    47      private OraclePreparedStatement insertStatement;
    48      private OraclePreparedStatement errorStatement;
    49      private CLOB clob;
    50
    51      private Hashtable namespaceToPrefix = null;
    52      private Hashtable prefixToNamespace = null;
    53      private String targetElementName = null;
    54
    55      private XMLDocument currentDocument;
    56      private Node currentNode;
    57
    58      private int documentCount = 0;
    59
    60      public SaxProcessor() {
    61          this.namespaceToPrefix = new Hashtable();
    62          this.prefixToNamespace = new Hashtable();
    63      }
    64
    65      private boolean isTargetElement(String elementName) {
    66          return ((this.currentDocument == null) &&
    67                  (elementName.equals(this.targetElementName)));
    68      }
    69
    70      public void startDocument() throws SAXException {
    71      }
    72
    73      public void endDocument() throws SAXException {
    74      }
    75
    76      public void startElement(String namespaceURI, String localName, String elementName, Attributes attrs)
    77      throws SAXException
    78      {
    79          if (DEBUG) {
    80              System.out.println("startElement() : URI = " + namespaceURI + ", localName = " + localName + ", elementName = " + elementNa
    me);
    81          }
    82          if (this.currentDocument == null)
    83          {
    84              if (DEBUG) {
    85                  System.out.println("startElement() : Checking for start of Fragment.");
    86              }
    87              if (isTargetElement(localName))
    88              {
    89                  if (DEBUG) {
    90                      System.out.println("startElement() : Starting New Document");
    91                  }
    92                  this.currentDocument = new XMLDocument();
    93                  this.currentNode = this.currentDocument;
    94                  XMLElement rootElement = createNewElement(namespaceURI, localName, elementName, attrs);
    95                  this.currentDocument.appendChild(rootElement);
    96                  this.currentNode = rootElement;
    97              }
    98          }
    99          else
    100          {
    101             XMLElement nextElement = createNewElement(namespaceURI, localName, elementName, attrs);
    102             this.currentNode.appendChild(nextElement);
    103             this.currentNode = nextElement;
    104          }
    105      }
    106
    107      public void endElement(String namespaceURI, String localName, String qName)
    108      throws SAXException
    109      {
    110          if (this.currentDocument != null)
    111          {
    112              if (this.currentNode.equals(this.currentDocument.getDocumentElement()))
    113              {
    114                  try
    115                  {
    116                    insertDocument();
    117                    this.currentDocument = null;
    118                  }
    119                  catch (SQLException sqlE)
    120                  {
    121                      throw new SAXException(sqlE);
    122                  }
    123                  catch (IOException ioe)
    124                  {
    125                      throw new SAXException(ioe);
    126                  }
    127              }
    128              else
    129              {
    130                  this.currentNode = this.currentNode.getParentNode();
    131              }
    132          }
    133      }
    134
    135      private XMLElement createNewElement(String namespaceURI, String localName,
    136                                          String elementName, Attributes attrs) {
    137          XMLElement newElement = null;
    138          if (namespaceURI != null) {
    139              if (this.namespaceToPrefix.containsKey(namespaceURI)) {
    140                  /* Namespace in already in Scope - create Element from Qualified Name */
    141                  newElement =
    142                      (XMLElement)this.currentDocument.createElement(elementName);
    143              } else {
    144                  /* Namespace is not already in Scope - create Element with namespace */
    145                  newElement =
    146                      (XMLElement) this.currentDocument.createElementNS(namespaceURI,
    147                                                                                elementName);
    148                  newElement.setPrefix((String)this.namespaceToPrefix.get(namespaceURI));
    149              }
    150          } else {
    151              newElement =
    152                  (XMLElement)this.currentDocument.createElement(localName);
    153          }
    154          addAttributes(newElement, attrs);
    155          if (this.currentNode.equals(this.currentDocument)) {
    156              addNamespaceDeclarations(newElement);
    157          }
    158          return newElement;
    159      }
    160
    161      private void addAttributes(Element element, Attributes attrs) {
    162          for (int i = 0; i < attrs.getLength(); i++) {
    163              if (attrs.getURI(i).equals("http://www.w3.org/2000/xmlns/")) {
    164              } else {
    165                  element.setAttribute(attrs.getQName(i), attrs.getValue(i));
    166              }
    167          }
    168      }
    169
    170      private void addNamespaceDeclarations(Element element) {
    171          Enumeration keys = this.namespaceToPrefix.keys();
    172          while (keys.hasMoreElements()) {
    173              String namespace = (String)keys.nextElement();
    174              String prefix = (String)namespaceToPrefix.get(namespace);
    175              Attr attr = null;
    176              if (prefix.equals("")) {
    177                  attr = this.currentDocument.createAttribute("xmlns");
    178                  attr.setValue(namespace);
    179                  element.setAttributeNode(attr);
    180              } else {
    181                  if (!prefix.equals(element.getPrefix())) {
    182                      attr =
    183                          this.currentDocument.createAttribute("xmlns:" + prefix);
    184                      attr.setValue(namespace);
    185                      element.setAttributeNode(attr);
    186                  }
    187              }
    188          }
    189      }
    190
    191      public void characters(char[] p0, int p1, int p2) throws SAXException {
    192          if (this.currentDocument != null) {
    193              StringWriter sw = new StringWriter();
    194              sw.write(p0, p1, p2);
    195              String value = sw.toString();
    196              Node textNode = this.currentDocument.createTextNode(value);
    197              this.currentNode.appendChild(textNode);
    198          }
    199      }
    200
    201      public void startPrefixMapping(String prefix,
    202                                     String uri) throws SAXException {
    203          this.namespaceToPrefix.put(uri, prefix);
    204          this.prefixToNamespace.put(prefix, uri);
    205      }
    206
    207      public void endPrefixMapping(String prefix) throws SAXException {
    208          Enumeration e = prefixToNamespace.keys();
    209          while (e.hasMoreElements()) {
    210              String thisPrefix = (String)e.nextElement();
    211              if (thisPrefix.equals(prefix)) {
    212                  String namespace =
    213                      (String)prefixToNamespace.remove(thisPrefix);
    214                  namespaceToPrefix.remove(namespace);
    215              }
    216          }
    217      }
    218
    219      public void ignorableWhitespace(char[] p0, int p1,
    220                                      int p2) throws SAXException {
    221          // throw new SAXException ("Un-Implemented Method: ingnoreableWhitespace");
    222      }
    223
    224      public void processingInstruction(String p0,
    225                                        String p1) throws SAXException {
    226          throw new SAXException("Un-Implemented Method: processingInstruction");
    227      }
    228
    229      public void setDocumentLocator(Locator p0) {
    230          // throw new SAXException ("Un-Implemented Method: setDocumentLocator");
    231      }
    232
    233      public void skippedEntity(String p0) throws SAXException {
    234          throw new SAXException("Un-Implemented Method: skippedEntity");
    235      }
    236
    237      public void doParse(BFILE bfile, String targetElement,
    238                             String targetTable, String errorTable) throws Exception {
    239              this.targetElementName = targetElement;
    240              String insertStatementText =
    241                  "insert into " + targetTable + " values (xmlParse(DOCUMENT ? WELLFORMED))";
    242              String errorStatementText =
    243                  "insert into " + errorTable + " values (xmlParse(DOCUMENT ? WELLFORMED))";
    244
    245              DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
    246              OracleDriver ora = new OracleDriver();
    247              this.dbConnection = (OracleConnection)ora.defaultConnection();
    248
    249              this.insertStatement =
    250                  (OraclePreparedStatement)this.dbConnection.prepareStatement(insertStatementText);
    251              this.errorStatement =
    252                  (OraclePreparedStatement)this.dbConnection.prepareStatement(errorStatementText);
    253
    254              this.clob =
    255                  CLOB.createTemporary(this.dbConnection, true, CLOB.DURATION_SESSION);
    256
    257              SAXParser parser = new SAXParser();
    258              parser.setAttribute(SAXParser.STANDALONE, Boolean.valueOf(true));
    259              parser.setValidationMode(SAXParser.NONVALIDATING);
    260              parser.setContentHandler(this);
    261              bfile.openFile();
    262              parser.parse(bfile.getBinaryStream());
    263              bfile.closeFile();
    264              this.insertStatement.close();
    265              this.errorStatement.close();
    266      }
    267
    268      private void insertDocument() throws SQLException, IOException {
    269          this.clob.truncate(0);
    270          Writer out = clob.setCharacterStream(0);
    271          this.currentDocument.print(out);
    272          out.close();
    273
    274          this.insertStatement.setClob(1, clob);
    275          this.insertStatement.execute();
    276
    277          this.documentCount++;
    278
    279          if (DEBUG) {
    280              System.out.println("insertDocument() : Document Inserted");
    281          }
    282      }
    283
    284      public static int parseBFile(BFILE bfile, String targetElement,
    285                             String targetTable, String errorTable) throws Exception {
    286          try {
    287            SaxProcessor processor = new SaxProcessor();
    288            processor.doParse(bfile,targetElement,targetTable,errorTable);
    289            return processor.documentCount;
    290          }
    291          catch (Exception e) {
    292            e.printStackTrace(System.out);
    293            throw e;
    294          }
    295
    296      }
    297  }
    298  ';
    299  begin
    300    if dbms_xdb.existsResource(:targetPath) then
    301      dbms_xdb.deleteResource(:targetPath);
    302    end if;
    303    res := dbms_xdb.createResource(:targetPath,javaSource);
    304  end;
    305  /
    Queuing DELETE Event
    PL/SQL procedure successfully completed.
    SQL> --
    SQL> set define on
    SQL> --
    SQL> create or replace and resolve java source
      2  named "&MODULE"
      3  using blob
      4  (
      5  select xdburiType('/public/JavaSource.java').getBlob(nls_charset_id('WE8ISO8859P1'))
      6  from dual
      7  )
      8  /
    old   2: named "&MODULE"
    new   2: named "SaxProcessor"
    Java created.
    SQL> show errors
    No errors.
    SQL> --
    SQL> declare
      2    shortname varchar2(128);
      3  begin
      4    shortname := dbms_java.shortname('&CLASS');
      5    execute immediate 'grant execute on "' || shortname || '" to public';
      6  end;
      7  /
    old   4:   shortname := dbms_java.shortname('&CLASS');
    new   4:   shortname := dbms_java.shortname('com/oracle/st/xmldb/pm/examples/SaxProcessor');
    PL/SQL procedure successfully completed.
    SQL> create or replace package SAX_PROCESSOR
      2  as
      3    procedure PARSE_BFILE(file BFILE, targetElement varchar2, targetTable varchar2, errorTable varchar2);
      4  end;
      5  /
    Package created.
    SQL> show errors
    No errors.
    SQL> --
    SQL> create or replace package body SAX_PROCESSOR
      2  as
      3  --
      4  procedure PARSE_BFILE(file BFILE, targetElement varchar2, targetTable varchar2, errorTable varchar2)
      5  AS LANGUAGE JAVA
      6     NAME 'com.oracle.st.xmldb.pm.examples.SaxProcessor.parseBFile( oracle.sql.BFILE, java.lang.String, java.lang.String, java.lang.Strin
    g)';
      7  end;
      8  /
    Package body created.
    SQL> show errors
    No errors.
    SQL> --
    SQL> drop table PO_TEST
      2  /
    Table dropped.
    SQL> create table PO_TEST of XMLTYPE
      2  /
    Table created.
    SQL> drop table PO_ERROR
      2  /
    Table dropped.
    SQL> create table PO_ERROR of XMLTYPE
      2  /
    Table created.
    SQL> create or replace directory xmldir as 'c:\temp'
      2  /
    Directory created.
    SQL> set serveroutput on
    SQL> --
    SQL> call SAX_PROCESSOR.PARSE_BFILE(bfilename('XMLDIR','testcase.xml'),'PurchaseOrder','PO_TEST','PO_ERROR')
      2  /
    call SAX_PROCESSOR.PARSE_BFILE(bfilename('XMLDIR','testcase.xml'),'PurchaseOrder','PO_TEST','PO_ERROR')
    ERROR at line 1:
    ORA-29549: class XFILES.com/oracle/st/xmldb/pm/examples/SaxProcessor has
    changed, Java session state cleared
    SQL> call SAX_PROCESSOR.PARSE_BFILE(bfilename('XMLDIR','testcase.xml'),'PurchaseOrder','PO_TEST','PO_ERROR')
      2  /
    Call completed.
    SQL> select count(*) from PO_TEST
      2  /
             3
    SQL> select * from PO_TEST
      2  /
    <PurchaseOrder xsi:noNamespaceSchemaLocation="http://xfiles:8080/home/SCOTT/poSo
    urce/xsd/purchaseOrder.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
    ">
      <Reference>AMCEWEN-20030409123336271PDT</Reference>
      <Actions>
        <Action>
          <User>KPARTNER</User>
        </Action>
      </Actions>
      <Reject/>
      <Requestor>Allan D. McEwen</Requestor>
      <User>AMCEWEN</User>
    <PurchaseOrder xsi:noNamespaceSchemaLocation="http://xfiles:8080/home/SCOTT/poSo
    urce/xsd/purchaseOrder.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
    ">
      <Reference>SKING-20030409123336321PDT</Reference>
      <Actions>
        <Action>
          <User>SKING</User>
        </Action>
      </Actions>
      <Reject/>
      <Requestor>Steven A. King</Requestor>
      <User>SKING</User>
    <PurchaseOrder xsi:noNamespaceSchemaLocation="http://xfiles:8080/home/SCOTT/poSo
    urce/xsd/purchaseOrder.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
    ">
      <Reference>SMCCAIN-20030409120030451PDT</Reference>
      <Actions>
        <Action>
          <User>SVOLLMAN</User>
        </Action>
      </Actions>
      <Reject/>
      <Requestor>Samuel B. McCain</Requestor>
      <User>SMCCAIN</User>
    SQL>

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

  • 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

  • Problem in parsing an XML using SAX parser

    Hai All,
    I have got a problem in parsing an XML using SAX parser.
    I have an XML (sample below) which need to be parsed
    <line-items>
    <item num="1">
         <part-number>PN1234</part-number>
         <quantity uom="ea">10</quantity>
         <lpn>LPN1060</lpn>
         <reference num="1">Line ref 1</reference>
         <reference num="2">Line ref 2</reference>
         <reference num="3">Line ref 3</reference>
    </item>
    <item num="2">
         <part-number>PN1527</part-number>
         <quantity uom="lbs">5</quantity>
         <lpn>LPN2152</lpn>
         <reference num="1">Line ref 1</reference>
         <reference num="2">Line ref 2</reference>
         <reference num="3">Line ref 3</reference>
    </item>
    <item num="n">
    </item>
    </line-items>
    There can be any number of items( 1 to n). I need to parse these
    item values using SAX parser and invoke a stored procedure for
    each item with its
    values(partnumber,qty,lpn,refnum1,refnum2,refnum3).
    Suppose if there are 100 items, i need to invoke the stored
    procedure sp1() 100 times for each item.
    I need to invoke the stored procedure in endDocument() method of
    SAX event handler and not in endelement() method.
    What is the best way to store those values and invoke the stored
    procedure in enddocument() method.
    Any help would br greatly appreciated.
    Thanks in advance
    Pooja.

    VO or ValueObject is a trendy new name for Beans.
    So just create an item class with variables for each of the sub elements.
    <item>
    <part-number>PN1234</part-number>
    <quantity uom="ea">10</quantity>
    <lpn>LPN1060</lpn>
    <reference num="1">Line ref 1</reference>
    <reference num="2">Line ref 2</reference>
    <reference num="3">Line ref 3</reference>
    </item>
    public class ItemVO
    String partNumber;
    int quantity;
    String quantityType;
    String lpn;
    List references = new ArrayList();
    * @return Returns the lpn.
    public String getLpn()
    return this.lpn;
    * @param lpn The lpn to set.
    public void setLpn(String lpn)
    this.lpn = lpn;
    * @return Returns the partNumber.
    public String getPartNumber()
    return this.partNumber;
    * @param partNumber The partNumber to set.
    public void setPartNumber(String partNumber)
    this.partNumber = partNumber;
    * @return Returns the quantity.
    public int getQuantity()
    return this.quantity;
    * @param quantity The quantity to set.
    public void setQuantity(int quantity)
    this.quantity = quantity;
    * @return Returns the quantityType.
    public String getQuantityType()
    return this.quantityType;
    * @param quantityType The quantityType to set.
    public void setQuantityType(String quantityType)
    this.quantityType = quantityType;
    * @return Returns the references.
    public List getReferences()
    return this.references;
    * @param references The references to set.
    public void setReferences(List references)
    this.references = references;

  • Problem in using SAX parser.

    Hai All,
    I have got a problem in using SAX parser.
    My XML looks like this:
    <authorizer>
    <first-name>HP</first-name>
    <last-name>Services</last-name>
    <phone>800-22-1984</phone>
    </authorizer>
    <destination>
    <first-name>John</first-name>
    <last-name>Doe</last-name>
    <company>John Doe Enterprises, Inc.</company>
    <department>Manufacturing</department>
    <phone>800-555-1234</phone>
    <address>
    <street-one>1654 Peachtree Str</street-one>
    <street-two>Suite Y</street-two>
    <city>Atlanta</city>
    <province>GA</province>
    <country>US</country>
    <postal-code>30326</postal-code>
    </address>
    </destination>
    my part of SAX parser code is:
    public void startElement (String name, AttributeList attrs)
    throws SAXException
    accumulator.setLength(0);
    public void characters (char buf [], int offset, int len)
    throws SAXException
    accumulator.append(buf, offset, len);
    public void endElement (String name)
    throws SAXException
    if (name.equals("first-name") )
    firstname=accumulator.toString().trim();
    if (name.equals("last-name"))
    lastname=accumulator.toString().trim();
    My problem is that i have to store the values of first-name and last-name.
    but i have that in both
    <authorizer> </authorizer> Tag and
    <destination> </destination>
    I need to retrive authorizer's firstname,lastname and
    destination's firstname and lastname.
    what i mean is i need to store authorizerFirstName,authorizerLastName
    destinationFirstname and destinationLastname.
    Pls let me know how to do that.
    Thanks in advance.
    Pooja.

    hi pooja,
    I think you are using DataHandler for parsing. Its deprecated. try using contentHandler . You can get the value of the element at the beginning. say for example
    <firstname>sdfs</firstname>
    the startElement will be firstname
    the next method that it invokes will be characters method which has the text associated with the element. I am sending a sample code for your problem. try using it .
    boolean m_boolinAuth = false;
    boolean m_boolinDest = false;
    boolean m_bAuthFName = false;
    boolean m_bAuthLName = false;
    public void startElement(String namespaceURI, String elementName, String qName, Attributes atts)
    //does the logic for startElement
    if(qName.equals("Authorization"))
    m_boolinAuth = true;
    m_boolinDest = false;
    else if(qName.equals("Destination"))
    m_boolinDest = true;
    m_boolinAuth = false;
    if(qName.equals("firstname"))
    m_bFirstName = true;
    if(qName.equals("lastname"))
    m_bLastName = true;
    public void characters(char[] ch, int start, int length)
    //does the logic for characters.
    String str = new String(ch,start,length);
    if(m_bFirstName)
    if(m_boolinAuth)
    m_strAuthFirstName =str;
    else if(m_boolinDest)
    m_strDestFirstName = str;
    m_bFirstName = false;
    if(m_bLastName)
    //same as first name case;
    }

Maybe you are looking for