SAX help

Hi all
I want to know how to get index of attribute with SAX using javax.xml.parsers.SAXParser ,but when i use Attributes getIndex(QualifiedName); method it returns -1 but a single attribute is present in XML File ,so i wana know why it happens?
thanks in advance

hi
try this.i dont know whether this is wht u meant.
public void startElement(String qname,Attribute attr)throws SAXException
for(int i=0; i<attr.getLength();i++)
                         System.out.println(attr.getIndex(attr.getQName(index)));
}

Similar Messages

  • I'm new to sax - Help

    Hi,
    Why am i not getting the localName in the endElement() when i use this class DefaultHandler
    The syntax says ,
    localName - The local name (without prefix), or the empty string if Namespace processing is not being performed.
    So how should i perform "Namespace processing"
    anyone know this ?
    -

    localName - The local name (without prefix), or the empty string if Namespace processing is not being performed.Most SAX parsers perform namespace processing on namespace qualifed elements by default, with an option to turn it off.
    The XML document you are parsing may or may not be using namespaces.
    If it does use namespaces, then the local name will be the local name of an element whose tag name is in a namespace. If the element's tag name is not in a namespace, then the local name may be empty. Whether or not is a parser implementation variation point.
    Use the qName to get a non-namespaced element's tag name.
    Some discussion as to whether SAX implementations follow the spirit of the XML namespaces spec. can be found here: http://lists.xml.org/archives/xml-dev/200205/msg01378.html
    Pete

  • Using MySQL with OEP

    Hi Team,
    I have an OEP running with Oracle DB but I need to move to MySQL.
    Has anyone done this?
    What is required?
    Thanks

    Here are the steps which should be used:
    1. Created a bundle jar for mysql driver(followed steps as per the OEP documentation )
        Goto $ORACLE_HOME/oep/bin in server installation directory
        Run the following script
    sh bundler.sh -source /scratch/sbishnoi/view_storage/sbishnoi_india/cep/wlevs_cql/release/target/server/oep/bin/mysql-connector-java-commercial-5.1.34-bin.jar -name mysql5 -version 5.1.34 -factory com.mysql.jdbc.jdbc2.optional.MysqlXADataSource com.mysql.jdbc.Driver -service javax.sql.XADataSource java.sql.Driver -targetdir .
    The generated jar will be in the current directory and its name will be mysql5_5.1.34.jar.
    Please note that the connector jar mysql-connector-java-commercial-5.1.34-bin.jar was part of MySQL Server installation and wasn't download it separately.
    2. Manually edit the MANIFEST.MF of newly generated jar mysql5_5.1.34.jar to remove unwanted imports which may cause you to download dependencies.
    The import section for my jar looks like as follows:
    Import-Package: javax.crypto,javax.xml.stream,javax.sql,javax.naming,javax.xml.transform.dom,javax.naming.spi,org.xml.sax,org.xml.sax.help
    ers,org.w3c.dom,javax.xml.transform.sax,javax.transaction.xa,javax.management,javax.xml.transform.stax,javax.xml.parsers,javax.xml.transfo
    rm,org.osgi.framework,javax.xml.transform.stream,javax.xml.datatype,javax.net.ssl,javax.net
    3.  Copy the driver bundle jar into following server directory inside domain directory:
    $ cp mysql5_5.1.34.jar …….user_projects/test_domain/defaultserver/modules/ext/
    Create modules/ext directories if it doesn’t exist and then copy the jar.
    4. Prior to starting server, Edit the server’s configuration to define the datasource.
    Here is  config.xml file which we tried:
    <data-source>
    <name>mysql</name>
        <data-source-params>
    <global-transactions-protocol>None</global-transactions-protocol>
    </data-source-params>
    <connection-pool-params>
    <test-table-name>SELECT 1 FROM DUAL</test-table-name>
    <initial-capacity>5</initial-capacity>
    <max-capacity>10</max-capacity>
    </connection-pool-params>
    <driver-params>
    <url>jdbc:mysql://10.159.165.60/mysql</url>
    <driver-name>com.mysql.jdbc.Driver</driver-name>
    <properties>
    <element><name>user</name><value>mysql</value></element>
    <element><name>password</name><value>mysql</value></element>
    <element><name>com.bea.core.datasource.serviceName</name><value>mysql5</value></element>
    <element><name>com.bea.core.datasource.serviceVersion</name><value>5.1.34</value></element>
    <element><name>com.bea.core.datasource.serviceObjectClass</name><value>javax.sql.XADataSource</value></element>
    </properties>
    <use-xa-data-source-interface>false</use-xa-data-source-interface>
    </driver-params>
    </data-source>
    5. Now Start the server. Make sure MySQL Database is running on the URL mentioned in config file.
    Although on server startup, you will see the following exception(not to worry about):
    [sbishnoi@adc2101019 defaultserver]$ sh startwlevs.sh
    Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=128m; support was removed in 8.0
    <Dec 19, 2014 6:39:52 AM PST> <Notice> <LibExt> <BEA-000000> <The extension library bundle "mysql5" was started successfully>
    <Dec 19, 2014 6:39:54 AM PST> <Notice> <LoggingService> <BEA-320400> <The log file /net/adc2101019/scratch/sbishnoi/view_storage/sbishnoi_india/cep/wlevs_cql/release/target/server/user_projects/test_domain/defaultserver/server.log will be rotated. Reopen the log file if tailing has stopped. This can happen on some platforms, such as Windows.>
    <Dec 19, 2014 6:39:54 AM PST> <Notice> <LoggingService> <BEA-320401> <The log file has been rotated to /net/adc2101019/scratch/sbishnoi/view_storage/sbishnoi_india/cep/wlevs_cql/release/target/server/user_projects/test_domain/defaultserver/server.log00014. Log messages will continue to be logged in /net/adc2101019/scratch/sbishnoi/view_storage/sbishnoi_india/cep/wlevs_cql/release/target/server/user_projects/test_domain/defaultserver/server.log.>
    <Dec 19, 2014 6:39:58 AM PST> <Error> <JDBC> <BEA-001112> <Test "select count(*) from SELECT 1 FROM DUAL" set up for pool "mysql" failed with exception: "com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT 1 FROM DUAL' at line 1".>
    <Dec 19, 2014 6:40:00 AM PST> <Error> <JDBC> <BEA-001112> <Test "select count(*) from SELECT 1 FROM DUAL" set up for pool "mysql" failed with exception: "com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT 1 FROM DUAL' at line 1".>
    <Dec 19, 2014 6:40:00 AM PST> <Error> <JDBC> <BEA-001111> <Unable to verify the test "select count(*) from SELECT 1 FROM DUAL" set up for pool "mysql". Connections will not be tested. The test will not be used by isValid either.>
    These are related to some configuration test query execution on database to ensure connectivity. The exception here is SQL syntax which is not a connectivity issue so we can safely assume that connection is obtained.

  • Can not initialize XML parser

    Can someone say how to initialize a SAX parser?
    When I try to do it, a SAXException occures.
    I think thats because no paser driver is loaded (as API docs say).
    How can I make it work?

    Try the following snippet (not compiled) with JDK 1.3 or higher (crimson included) to get the idea:
    class DummyContentHandler implements org.xml.sax.ContentHandler{
            int count = 0;
            public void startDocument() throws org.xml.sax.SAXException {}       
            public void characters(char[] values, int param, int param2) throws org.xml.sax.SAXException {}       
            public void ignorableWhitespace(char[] values, int param, int param2) throws org.xml.sax.SAXException {}       
            public void processingInstruction(java.lang.String str, java.lang.String str1) throws org.xml.sax.SAXException {  }
            public void startPrefixMapping(java.lang.String str, java.lang.String str1) throws org.xml.sax.SAXException {}
            public void endDocument() throws org.xml.sax.SAXException {}
            public void skippedEntity(java.lang.String str) throws org.xml.sax.SAXException {}
            public void setDocumentLocator(org.xml.sax.Locator locator) {}
            public void endPrefixMapping(java.lang.String str) 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 {
                count++;
            public void endElement(java.lang.String str,
                   java.lang.String str1,
                   java.lang.String str2) throws org.xml.sax.SAXException {}
      public class SAXer{
      // Helper method
      public static void parseWithSax(org.xml.sax.InputSource is,org.xml.sax.ContentHandler ch) throws Exception{
              javax.xml.parsers.SAXParserFactory spf =
                javax.xml.parsers.SAXParserFactory.newInstance();
              spf.setNamespaceAware(true);
              org.xml.sax.XMLReader p = (org.xml.sax.XMLReader)spf.newSAXParser().getXMLReader();  
              p.setContentHandler(ch);
              p.parse(is);
      public static void main(String[] args) throws Exception{
           // Set factory
           System.setProperty("javax.xml.parsers.SAXParserFactory", "org.apache.crimson.jaxp.SAXParserFactoryImpl");
           // Initialize content handler
            DummyContentHandler ch = new DummyContentHandler(); 
           String test = "<a><b/></a>";
           parseWithSax(new org.xml.sax.InputSource(new java.io.StringReader(test)),ch);
            System.out.println("Elementcount:" + ch.count);
      }

  • Getting org.xml.sax.SAXNotRecognizedException in Java mapping. Help!

    Hi Experts
       I have written a java code for schema validating XI message.
    my java code:
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import com.sap.aii.mapping.api.StreamTransformation;
    import java.io.*;
    import java.util.Map;
    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import org.xml.sax.helpers.*;
    public class P2PValidation extends DefaultHandler implements StreamTransformation{
         private Map map;
         private OutputStream out;
         //Constants when using XML Schema for SAX parsing.
         static final String JAXP_SCHEMA_LANGUAGE =
         "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
         static final String W3C_XML_SCHEMA =
         "http://www.w3.org/2001/XMLSchema";
         static final String JAXP_SCHEMA_SOURCE =
         "http://java.sun.com/xml/jaxp/properties/schemaSource";
         public void setParameter (Map param){
              map = param;
         public void execute (InputStream in, OutputStream out)
         throws com.sap.aii.mapping.api.StreamTransformationException {
            DefaultHandler handler = this;
              SAXParserFactory factory = SAXParserFactory.newInstance();
              // Obtain an object of class javax.xml.parsers.SAXParser,
             factory.setNamespaceAware(true);
             factory.setValidating(true);
              try {
                   SAXParser saxParser = factory.newSAXParser();
                   // Setup the schema file
                   //saxParser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
                   //saxParser.setProperty(JAXP_SCHEMA_SOURCE, new File("IOReqMsgSchema.xsd"));
                   saxParser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
                   saxParser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", new File("IOReqMsgSchema.xsd"));
                  //System.out.println("Parsing");
                  this.out = out;
                   saxParser.parse(in, handler);
              catch (Exception t){
                   t.printStackTrace();
         private void write (String s) throws SAXException{
              try{
                   out.write(s.getBytes()); out.flush();
              catch (IOException e){
                   throw new SAXException("I/O error", e);
         public void startDocument () throws SAXException{
              write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
              write("<ns0:ValidInternalOrder xmlns:ns0=\"http://www.xyz.com/Gopal\">");
         public void endDocument () throws SAXException {
              write("</ns0:ValidInternalOrder>");
              try { out.flush();
              catch (IOException e) {
                   throw new SAXException("I/O error", e);
         public void startElement (String namespaceURI, String sName, String qName, Attributes attrs)
         throws SAXException {
            System.out.println("sName="sName" qName="+sName);
                if(sName.equals(qName))
                   write("<"sName">");
         public void endElement (String namespaceURI, String sName, String qName) throws SAXException {
              if(sName.equals(qName))
                   write("</"sName">");
         public void characters (char buf[], int offset, int len)
         throws SAXException {
              String s = new String(buf, offset, len);
              write (s);
         public void error(SAXParseException se) throws SAXException {
              throw se;
    But when I run the code in my local machine or in Xi i am getting the error:
    org.xml.sax.SAXNotRecognizedException:
            at com.inqmy.lib.xml.parser.SAXParser.setProperty(SAXParser.java:111)
            at com.inqmy.lib.jaxp.SAXParserImpl.setProperty(SAXParserImpl.java:51
            at P2PValidation.execute(P2PValidation.java:38)
    What is wrong with the properties I have set for schema validatation?
    //Constants when using XML Schema for SAX parsing.
         static final String JAXP_SCHEMA_LANGUAGE =
         "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
         static final String W3C_XML_SCHEMA =
         "http://www.w3.org/2001/XMLSchema";
         static final String JAXP_SCHEMA_SOURCE =
         "http://java.sun.com/xml/jaxp/properties/schemaSource";
    Kindly help me understand how to correct this error. What are the correct values for properties?
    Please help! URGENT!!!
    Thanks
    Gopal
    Edited by: gopalkrishna baliga on Mar 4, 2008 12:45 PM

    Hi Gabriel,
       I have already seen that link but did not get any solution yet.
      Please help me!
    -Gopal

  • SAX error parsing by element. need help!

    I am trying to develop a small method to that can parse an xml file and return an elements value. I got some code to build a SAXHandler. I have build the SAXHandler and have compiled it no problem.
    import java.io.*;
    import java.util.Hashtable;
    import org.xml.sax.*;
    import org.xml.sax.helpers.*;
    public class SAXHandler extends DefaultHandler {
    private Hashtable table = new Hashtable();
    private String currentElement = null;
    private String currentValue = null;
    public void setTable(Hashtable table) {
    this.table = table;
    public Hashtable getTable(){
    return table;
    public void startElement(String tag, Attributes attrs)
    throws SAXException {
    currentElement = tag;
    public void characters(char[] ch, int start, int length)
    throws SAXException {
    currentValue = new String(ch, start, length);
    public void endElement(String name) throws SAXException {
    if (currentElement.equals(name)) {
    table.put(currentElement, currentValue);
    I am using the following code to read the file in and parse it.
    public String getXMLElement(){
    try {
    File xmlFile = new File(appDataFile);
    FileReader xmlRead = new FileReader(xmlFile);
    XMLReader xmlParser;
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    SAXHandler handler = new SAXHandler();
    sp.parse(new InputSource(xmlRead), handler);
    i am recieving the following error when I try to run the servlet
    javax.servlet.ServletException: Cannot allocate servlet instance for path /JDtrack/servlet/JDTrack
    what makes this wierd is that is i take out the line
    sp.parse(new InputSource(xmlRead), handler);
    I do not get the error.
    I am newer to java and could use all the help I can get
    thanks.

    A few things to try to help identify the problem:
    -Create and InputSource before parsing the file. If the InputSource cannot be created, there may be a problem with accessing the file from your servlet.
    -Write a quick program to do the same thing from an application. If you can do this outside the servlet container, it may be a problem from running inside the servlet container.
    -The code you listed is in a try block, however the catch block is not listed. If you are not already doing so, place debug message (to console or log) from inside each catch block. If an exception is thrown but not handled corrrectly, the servlet container may just throw a ServletException.
    Hope this helps.

  • Org.xml.sax.SAXException error please help me out.............

    hi
    if any one can help me out pls it would be greate favour ...................
    iam new to webservice
    iam getting this error when i run the client program
    C:\jakarta-tomcat-4.1.31\webapps\axis>java AttachmentServiceClient
    org.xml.sax.SAXException: Deserializing parameter 'sku': could not find deserializer for type {http://www.w3.org/2001/XMLSchema}string
    iam using tomcat4.1, axis-1_3
    This is service file
    // SparePartAttachmentService.java
    import javax.activation.DataHandler;
    import java.io.*;
    public class SparePartAttachmentService {
    public SparePartAttachmentService(){}
    public String addImage (String sku, DataHandler dataHandler) {
    try {
    String filepath = "c:/wrox_axis/photo/" + sku +
    "-image.jpg";
    FileOutputStream fout = new FileOutputStream(new File (filepath));
    BufferedInputStream in =
    new BufferedInputStream(dataHandler.getInputStream());
    while (in.available()!= 0) {
    System.out.println("inside while");
    fout.write(in.read());
    } catch (Exception e) {
    return e.toString();
    return "Image: " + sku + " has been added successfully!!";
    This is wsdd file
    <deployment
    xmlns="http://xml.apache.org/axis/wsdd/"
    xmlns:java="http://xml.apache.org/axis/wsdd/providers/java"
    xmlns:ns1="AttachmentService">
    <service name="AttachmentService" provider="java:RPC">
    <parameter name="className"
    value="SparePartAttachmentService"/>
    <parameter name="allowedMethods"
    value="addImage"/>
    </service>
    <typeMapping qname="ns1:DataHandler"
    languageSpecificType="java:javax.activation.DataHandler"
    serializer="org.apache.axis.encoding.ser.
    JAFDataHandlerSerializerFactory"
    deserializer="org.apache.axis.encoding.ser.
    JAFDataHandlerDeserializerFactory"
    encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
    </deployment>
    This is client file
    // AttachmentServiceClient.java
    import java.net.URL;
    import org.apache.axis.client.Service;
    import org.apache.axis.client.Call;
    import org.apache.axis.encoding.XMLType;
    import java.io.*;
    import javax.xml.rpc.ParameterMode;
    import javax.xml.namespace.QName;
    import org.apache.axis.encoding.ser.JAFDataHandlerSerializerFactory;
    import org.apache.axis.encoding.ser.JAFDataHandlerDeserializerFactory;
    import javax.activation.FileDataSource;
    import javax.activation.DataHandler;
    public class AttachmentServiceClient {
    public AttachmentServiceClient(){}
    public static void main (String args[]) {
    try {
    String filename = "C:/jakarta-tomcat-4.1.31/webapps/axis/baby.jpg";
    System.out.println("filename " +filename);
    // Create the data for the attached file.
    DataHandler dhSource = new DataHandler (new
    FileDataSource (filename));
    System.out.println("filename " +dhSource);
    // EndPoint URL for the SparePartPrice Web Service
    String endpointURL =
    "http://localhost:8080/axis/services/AttachmentService";
    // Method Name to invoke for the Attachment Web Service
    String methodName = "addImage";
    // Create Call object and set parameters
    Service service = new Service();
    Call call = (Call) service.createCall();
    call.setTargetEndpointAddress (new java.net.URL(endpointURL));
    call.setOperationName (new QName("AttachmentService",
    methodName));
    call.addParameter("sku", XMLType.XSD_STRING,
    ParameterMode.IN);
    QName qname = new QName("AttachmentService", "DataHandler");
    call.addParameter("image", qname, ParameterMode.IN);
    // register the SparePartBean class
    call.registerTypeMapping(dhSource.getClass(), qname,
    JAFDataHandlerSerializerFactory.class,
    JAFDataHandlerDeserializerFactory.class);
    call.setReturnType(XMLType.XSD_STRING);
    // Setup the Parameters i.e. the Part SKU to be passed as
    // input parameter to the Attachment Web Service
    Object[] params = new Object[] { "SKU-111", dhSource };
    // Invoke the SparePartPrice Web Service
    String result = (String) call.invoke(params);
    // Print out the result
    System.out.println("The response: " + result);
    } catch (Exception e) {
    System.err.println(e.toString());
    }

    hi
    if any one can help me out pls it would be greate favour ...................
    iam new to webservice
    iam getting this error when i run the client program
    C:\jakarta-tomcat-4.1.31\webapps\axis>java AttachmentServiceClient
    org.xml.sax.SAXException: Deserializing parameter 'sku': could not find deserializer for type {http://www.w3.org/2001/XMLSchema}string
    iam using tomcat4.1, axis-1_3
    This is service file
    // SparePartAttachmentService.java
    import javax.activation.DataHandler;
    import java.io.*;
    public class SparePartAttachmentService {
    public SparePartAttachmentService(){}
    public String addImage (String sku, DataHandler dataHandler) {
    try {
    String filepath = "c:/wrox_axis/photo/" + sku +
    "-image.jpg";
    FileOutputStream fout = new FileOutputStream(new File (filepath));
    BufferedInputStream in =
    new BufferedInputStream(dataHandler.getInputStream());
    while (in.available()!= 0) {
    System.out.println("inside while");
    fout.write(in.read());
    } catch (Exception e) {
    return e.toString();
    return "Image: " + sku + " has been added successfully!!";
    This is wsdd file
    <deployment
    xmlns="http://xml.apache.org/axis/wsdd/"
    xmlns:java="http://xml.apache.org/axis/wsdd/providers/java"
    xmlns:ns1="AttachmentService">
    <service name="AttachmentService" provider="java:RPC">
    <parameter name="className"
    value="SparePartAttachmentService"/>
    <parameter name="allowedMethods"
    value="addImage"/>
    </service>
    <typeMapping qname="ns1:DataHandler"
    languageSpecificType="java:javax.activation.DataHandler"
    serializer="org.apache.axis.encoding.ser.
    JAFDataHandlerSerializerFactory"
    deserializer="org.apache.axis.encoding.ser.
    JAFDataHandlerDeserializerFactory"
    encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
    </deployment>
    This is client file
    // AttachmentServiceClient.java
    import java.net.URL;
    import org.apache.axis.client.Service;
    import org.apache.axis.client.Call;
    import org.apache.axis.encoding.XMLType;
    import java.io.*;
    import javax.xml.rpc.ParameterMode;
    import javax.xml.namespace.QName;
    import org.apache.axis.encoding.ser.JAFDataHandlerSerializerFactory;
    import org.apache.axis.encoding.ser.JAFDataHandlerDeserializerFactory;
    import javax.activation.FileDataSource;
    import javax.activation.DataHandler;
    public class AttachmentServiceClient {
    public AttachmentServiceClient(){}
    public static void main (String args[]) {
    try {
    String filename = "C:/jakarta-tomcat-4.1.31/webapps/axis/baby.jpg";
    System.out.println("filename " +filename);
    // Create the data for the attached file.
    DataHandler dhSource = new DataHandler (new
    FileDataSource (filename));
    System.out.println("filename " +dhSource);
    // EndPoint URL for the SparePartPrice Web Service
    String endpointURL =
    "http://localhost:8080/axis/services/AttachmentService";
    // Method Name to invoke for the Attachment Web Service
    String methodName = "addImage";
    // Create Call object and set parameters
    Service service = new Service();
    Call call = (Call) service.createCall();
    call.setTargetEndpointAddress (new java.net.URL(endpointURL));
    call.setOperationName (new QName("AttachmentService",
    methodName));
    call.addParameter("sku", XMLType.XSD_STRING,
    ParameterMode.IN);
    QName qname = new QName("AttachmentService", "DataHandler");
    call.addParameter("image", qname, ParameterMode.IN);
    // register the SparePartBean class
    call.registerTypeMapping(dhSource.getClass(), qname,
    JAFDataHandlerSerializerFactory.class,
    JAFDataHandlerDeserializerFactory.class);
    call.setReturnType(XMLType.XSD_STRING);
    // Setup the Parameters i.e. the Part SKU to be passed as
    // input parameter to the Attachment Web Service
    Object[] params = new Object[] { "SKU-111", dhSource };
    // Invoke the SparePartPrice Web Service
    String result = (String) call.invoke(params);
    // Print out the result
    System.out.println("The response: " + result);
    } catch (Exception e) {
    System.err.println(e.toString());
    }

  • SAX error need help

    I am trying to develop a small method to that can parse an xml file and return an elements value. I got some code to build a SAXHandler. I have build the SAXHandler and have compiled it no problem.
    import java.io.*;
    import java.util.Hashtable;
    import org.xml.sax.*;
    import org.xml.sax.helpers.*;
    public class SAXHandler extends DefaultHandler {
    private Hashtable table = new Hashtable();
    private String currentElement = null;
    private String currentValue = null;
    public void setTable(Hashtable table) {
    this.table = table;
    public Hashtable getTable(){
    return table;
    public void startElement(String tag, Attributes attrs)
    throws SAXException {
    currentElement = tag;
    public void characters(char[] ch, int start, int length)
    throws SAXException {
    currentValue = new String(ch, start, length);
    public void endElement(String name) throws SAXException {
    if (currentElement.equals(name)) {
    table.put(currentElement, currentValue);
    I am using the following code to read the file in and parse it.
    public String getXMLElement(){
    try {
    File xmlFile = new File(appDataFile);
    FileReader xmlRead = new FileReader(xmlFile);
    XMLReader xmlParser;
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    SAXHandler handler = new SAXHandler();
    sp.parse(new InputSource(xmlRead), handler);
    i am recieving the following error when I try to run the servlet
    javax.servlet.ServletException: Cannot allocate servlet instance for path /JDtrack/servlet/JDTrack
    what makes this wierd is that is i take out the line
    sp.parse(new InputSource(xmlRead), handler);
    I do not get the error.
    I am newer to java and could use all the help I can get
    thanks.

    Have you tried this:
    String uri = xmlFile.toString();
    sp.parse("file:/"+uri);
    here's my code from my app
    try{
           MyParseingApp loader = new MyParseingApp();
           SAXParserFactory spf =   SAXParserFactory.newInstance();
           SAXParser sp = spf.newSAXParser();
           ParserAdapter pa = new ParserAdapter(sp.getParser());
           pa.setContentHandler(loader);
           pa.parse("file:/"+uri);
          catch(Exception ex){ System.out.println("......."+ex);}Here's an excellent link for xml and SAX parser's
    http://www.troubleshooters.com/tpromag/200103/codexercises.htm#_saxjava
    Jim

  • I need help using a SAX parser

    Hello,
    I have a class that goes out to the web and retrieves an xml document w/o ever writing it to disk. I like to parse that object using SAX and a class that extends HandlerBase. Can any one show me how to parse an xml document that lives in memory rather than in a file? I've found many examples, but all of them assume you are reading from a file system. Any help is greatly appreciated.
    Here is the jist of my code :
    // Class 1 makes a request to another server based on some variable data. I've created a messenger object that handles all of the communications and returns the data in a DataInputStream
    XMLMessage xml = new XMLMessage();
    xml.createRequest(args[0],args[1],args[2]);
    XMLMessenger messenger = new XMLMessenger(xml.getDoc());
    DataInputStream dis = messenger.transferDocument();
    ResponseObj resp = new ResponseObj();
    resp.read(dis);
    System.out.println(resp.getvalue1() + "*" + resp.getvalue2()+ "*");
    // Class 2 is the ResponseObj and I want to use something similar to this read method, but
    // I can't get it to work with a data stream, instead of a string that represents a file.
    public void read(String filename) throws java.lang.Exception {
    Class c = Class.forName("com.ibm.xml.parser.SAXDriver");
         org.xml.sax.Parser parser = (org.xml.sax.Parser)c.newInstance();
         parser.setDocumentHandler(this);
         parser.parse(filename);

    Thanks for you help. I've modified my read() method to work like this :
    org.xml.sax.Parser parser = new com.ibm.xml.parser.SAXDriver();
    parser.setDocumentHandler(this);
    InputSource is = new InputSource(dis);
    parser.parse(is);
    This makes sense, but I'm still not getting any thing returned from the startElement(),characters(), or endElement() methods. It reports no errors, it just doesn't happen. Do you have any suggestions on how to debug this? I'm stumped, but really need to get this working.

  • Help appending dtd's to XML programmatically(SAX parser)

    Hi
    If i want to validate an xml by writing a dtd and if i want to append that dtd to my xml programattically then how will i do it
    i am using java's sax parser currently .
    can any one help me out.
    Reply will b appritiated
    Regards
    Geetanjali P.

    Parsers are for inputting XML data. Your question is about outputting XML data, so your choice of parser is irrelevant. What is relevant is how you are outputting your XML, and you didn't say anything about that. So please do.

  • XML to HTMLusing SAX....help

    I need to write a program that converts XML documents into HTML documents using SAX. I've never used SAX before and am not that familiar with XML. I went over a tutorial ( http://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/sax/index.html ) yet am still completely lost regarding what I should be doing. Would anyone give me some foundation on what I need or where I should look or what I should be doing? I just need help.

    It is all in that tutorial. So if you don't understand it, read it again. Fiddle around with the code there and see what it does. And also, try to get the "using SAX" requirement removed and see if "using XSLT" is any easier.

  • Please help on SAX

    Hi guys,
    i got the following xml :
    <root>
    <applications>
    <application id="CUP">
    <area id="folders">
    <area id="foi1">
    <param id="pam1">C:\app\yak1</param>
    <param id="pam2">1</param>
    <param id="pam3">2</param>
    </area>
    <area id="foi2">
    <param id="pam1">C:\app\yak2</param>
    <param id="pam2">2</param>
    <param id="pam3">1</param>
    </area>
    </area>
    <area id="dao-group-mapping">
    <param id="US">C:\app\yak1\myapp1.txt,C:\app\yak1\myapp2.txt</param>
    <param id="UK">C:\app\yak1\myapp3.txt</param>
    <param id="CN">C:\app\yak1\myapp4.txt</param>
    </area>
    </application>
    </applications>
    </root>
    and code below:
    public class CupConfigParserHandler extends DefaultHandler {
    private Map<String, FolderInfo> folderInfoMap;
    private Map<String, ArrayList> daoMappingMap;
    public static void main(String[] args) {
    CupConfigParserHandler cupConfigParserHandler = new CupConfigParserHandler ();
    cupConfigParserHandler
    .parseDocument("c:/eclipse/cup/cup-config.xml");
    public CupConfigParserHandler(String filePath) {
    folderInfoMap = new HashMap();
    folderInfoMap = new HashMap();
    try {
    init(filePath);
    } catch (Exception e) {
    e.printStackTrace();
    private void init(String filePath) throws IOException, SAXException {
    // Use the default (non-validating) parser
    SAXParserFactory factory = SAXParserFactory.newInstance();
    try {
    // Parse the input
    SAXParser saxParser = factory.newSAXParser();
    saxParser.parse(new File(filePath), this);
    } catch (Throwable t) {
    t.printStackTrace();
    private void parseDocument(String filePath) {
    // get a factory
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {
    // get a new instance of parser
    SAXParser sp = spf.newSAXParser();
    // parse the file and also register this class for call backs
    sp.parse(filePath, this);
    } catch (SAXException se) {
    se.printStackTrace();
    } catch (ParserConfigurationException pce) {
    pce.printStackTrace();
    } catch (IOException ie) {
    ie.printStackTrace();
    } catch (Exception e) {
    e.printStackTrace();
    public void startElement(String ns, String ln, String qname, Attributes atts)
    throws SAXException {
    public void characters(char[] ch, int offset, int length)
    throws SAXException {
    public void endElement(String ns, String ln, String qname)
    throws SAXException {
    I am not sure how to fill up the startElement and endElement methods. I just need to fill up the folderInfoMap and daoMappingMap. Those area element under "folders" area element will grow in future. So how do I like once the program detected area element with id = "folders", it will put everything under "folders" elements into a map. I can't use any open source. Please help. Thanks !
    Gains

    Hi
    Plesae follow this link for an example of JAVA mapping using SAX parser
    http://objectissues.blogspot.com/2006/05/sample-sax-parser.html
    http://www.roseindia.net/xml/sax/EmployeeDetails.shtml
    regards
    sandeep
    Edited by: sandeep sharma on Dec 16, 2008 5:50 AM

  • Help setting up Aelfred and SAX for MIDP

    This relates to chapter 11 & 12 of Yu Feng book Wireless Java Programming with J2Me.
    Where exactly do you install Aelfred and Sax? What variables have to be set in the class path or what jar files have to be placed where.
    I can't compile my application because the class files that come with Aelfred can't find java.io.*; from the import Statement in the class file.
    The above class file is located in the4 SRC directory of my application.

    I've just realised that you have to manually remove some stuff from the classes such as reference to J2Se classes.
    How do you do this.

  • SAX Parser Bug? Help!

    Javadoc for the SAX 1.0 API states its should be possible to reuse a parser object to parse one document after another. I have not been able to do this - I keep getting and error "EOF expected" even though endDocument() in HandlerBase has been called.
    Is this a bug?
    Thanks much...

    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Joshua Introne ([email protected]):
    Javadoc for the SAX 1.0 API states its should be possible to reuse a parser object to parse one document after another. I have not been able to do this - I keep getting and error "EOF expected" even though endDocument() in HandlerBase has been called.
    Is this a bug?
    Thanks much...<HR></BLOCKQUOTE>
    Sorry - this isn't quite right. The final tag is parsed, but endDocument is never called. How can I get that event to be thrown without closing the stream feeding the inputSource?

  • Sax parser problem plz help

    hi !!!!!!!!!!!!
    Im using a SAX parser to parse an xml file im successful in doing it i got tit parse after parising i want the value of a particular tag for example i have a tag as
    <filtername>datasource</filtername>
    i want datasource after parsing the xml and without using DOM concept how do i do it please help

    hi i have a parser for start parsing and for start element
    when im doing this i get the complete xml parsed after the xml is parsed how do i get it i still could not get how to soak the characters .....
    private void startParsing()
              try
                   InputStream instream = getClass().getClassLoader().getResourceAsStream(contextFile);
                   InputSource in = new InputSource(instream);
                   SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
                   XMLReader reader = parser.getXMLReader();
                   reader.setContentHandler(this);
                   reader.parse(in);
              catch(ParserConfigurationException pce)
                   System.out.println(pce);
              catch(SAXException se)
                   System.out.println(se);
              catch(IOException ie)
                   System.out.println(ie);
         public void startElement(String uri,String localName,String qName,Attributes attributes)
              System.out.format("uri : %s localName %s qName %s %n",uri,localName,qName);
    so now i have an attribut but i need content of the opening and closingtag like
    attribute is name
    <name>jack</name>
    im successfull in getting name but now i want jill ....

Maybe you are looking for