Issue with mapping XML to Java using SAX API

I am using SAX API to Map XML Documents To Java. Is it possible to differentiate the elements based on the attribute rather than localname or element name in SAX API? because I am having the below xml structure. In SAX API we are processing the element values based on start/End Element name.
<?xml version="1.0" encoding="UTF-8"?>
<response>
<result name="response">
<doc>
<str name="art_id">192201910</str>
<str name="title">test</str>
<arr name="author">
<str>Darrell Dunn</str>
<str>William </str>
</arr>
<arr name="tax">
<str>113243335</str>
<str>233454666</str>
</arr>
</doc>
<doc>
<str name="art_id">192201911</str>
<str name="title">test2</str>
<arr name="author">
<str>Darrell Dunn1</str>
<str>William 1</str>
</arr>
</doc>
</result>
</response>
I want to map the elements based on attributes such as
classobj.art_id, classobj.title, classobj.tax[]. I have wriiten code below, but I am not getting the proper result.
import org.xml.sax.;
import org.xml.sax.helpers.;
import java.io.;
import java.util.;
import common.;
public class XmltoObjectHandler extends DefaultHandler{
/* Creates a new instance of XmltoObjectHandler */
public XmltoObjectHandler() {
// Local SolrDocument object to collect
// document XML data.
private XmlDocument doc = new XmlDocument();
// Local list of solr documents items...
private Vector xmlDocuments = new Vector();
// Local current solr document reference...
private XmlDocument currentSolrDoc;
// Buffer for collecting data from
// the "characters" SAX event.
private CharArrayWriter contents = new CharArrayWriter();
// Override methods of the DefaultHandler class
// to gain notification of SAX Events.
// See org.xml.sax.ContentHandler for all available events.
public void startElement( String namespaceURI,
String localName,
String qName,
Attributes attr ) throws SAXException {
if ( localName.equals( "doc" ) ) {
currentXmlDoc = new XmlDocument();
solrDocuments.addElement( currentSolrDoc );
if( localName.equals("str"){
for ( int i = 0; i < attr.getLength(); i++ ){
if("art_id".equals(attr.getValue(i))){
currentSolrDoc.art_id = contents.toString();
if("title".equals(attr.getValue(i))){
currentSolrDoc.title = contents.toString();
public void endElement( String namespaceURI,
String localName,
String qName ) throws SAXException {
public void characters( char[] ch, int start, int length )
throws SAXException {
contents.write( ch, start, length );
public Vector getxmlDocuments() {
return solrDocuments;
public static void main( String[] argv ){
System.out.println( "Example4:" );
try {
// Create SAX 2 parser...
XMLReader xr = XMLReaderFactory.createXMLReader();
// Set the ContentHandler...
XmltoObjectHandler ex4 = new XmltoObjectHandler();
xr.setContentHandler( ex4 );
// Parse the file...
xr.parse( new InputSource(new FileReader( "xmlfile.xml" )));
// Display all documents items...
XmlDocument i;
Vector items = ex4.getxmlDocument();
Enumeration e = items.elements();
while( e.hasMoreElements()){
i = (XmlDocument) e.nextElement();
System.out.println(i.art_id+"\n");
System.out.println(i.title+"\n");
}catch ( Exception e ) {
e.printStackTrace();
Can anybody help me how to process this type of xml. Is there any other way we can do this? I am trying for two days. It is a big deadlock for me. any help greatly appriciated. Thanks in advance.

I added my code inside code tags...
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.io.*;
import java.util.*;
import common.*;
public class XmltoObjectHandler extends DefaultHandler{
    /** Creates a new instance of XmltoObjectHandler */
    public XmltoObjectHandler() {
    // Local SolrDocument object to collect
    // document XML data.
    private XmlDocument doc = new XmlDocument();
    // Local list of solr documents items...
    private Vector xmlDocuments = new Vector();
    // Local current solr document reference...
    private XmlDocument currentSolrDoc;
    // Buffer for collecting data from
    // the "characters" SAX event.
    private CharArrayWriter contents = new CharArrayWriter();  
    // Override methods of the DefaultHandler class
    // to gain notification of SAX Events.
    // See org.xml.sax.ContentHandler for all available events.
    public void startElement( String namespaceURI,
            String localName,
            String qName,
            Attributes attr ) throws SAXException {
          if ( localName.equals( "doc" ) ) {
            currentXmlDoc = new XmlDocument();
            solrDocuments.addElement( currentSolrDoc );
          if( localName.equals("str"){
               for ( int i = 0; i < attr.getLength(); i++ ){               
                if("art_id".equals(attr.getValue(i))){
                         currentSolrDoc.art_id = contents.toString();
                    if("title".equals(attr.getValue(i))){
                         currentSolrDoc.title = contents.toString();
    public void endElement( String namespaceURI,
            String localName,
            String qName ) throws SAXException {      
    public void characters( char[] ch, int start, int length )
    throws SAXException {       
        contents.write( ch, start, length );       
    public Vector getxmlDocuments() {
        return solrDocuments;
    public static void main( String[] argv ){       
        System.out.println( "Example4:" );
        try {          
            // Create SAX 2 parser...
            XMLReader xr = XMLReaderFactory.createXMLReader();           
            // Set the ContentHandler...
            XmltoObjectHandler ex4 = new XmltoObjectHandler();
            xr.setContentHandler( ex4 );           
            // Parse the file...
            xr.parse( new InputSource(new FileReader( "xmlfile.xml" )));          
            // Display all documents items...
            XmlDocument i;
            Vector items = ex4.getxmlDocument();
            Enumeration e = items.elements();
            while( e.hasMoreElements()){
                i = (XmlDocument) e.nextElement();
                System.out.println(i.art_id+"\n");
                    System.out.println(i.title+"\n");
        }catch ( Exception e ) {
            e.printStackTrace();
}

Similar Messages

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

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

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

  • Issue with inbound xml..

    Hi All,
    We have an issue with inbound XML :
    XML structure is as follows:
    <?xml version="1.0" encoding="UTF-8" ?>
    <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <SOAP-ENV:Header>
          <Q-ENV:Header>
                  </Q-ENV:Header>
        </SOAP-ENV:Header>
        <SOAP-ENV:Body>
          <Q-ENV:Body>
            <Q-ENV:Content-Type>text/xml</Q-ENV:Content-Type>
            <Q-ENV:Message-Type>xCBL</Q-ENV:Message-Type>
            <Q-ENV:Encoding>UTF-8</Q-ENV:Encoding>
            <Q-ENV:Message-Body>
              <?xml version="1.0"?>
    <?soxtype urn:x-commerceone:document:com:commerceone:XCBL30:XCBL30.sox$1.0?>
    <OrderResponse>
    The issue is see at the <Q-ENV:Message-Body>  we are receiving  <?soxtype urn:x-commerceone:document:com:commerceone:XCBL30:XCBL30.sox$1.0?> for OrderResponse header ..it is neither validating as valid xml or unable to read the items after that namespace with graphical mapping or xslt ..if anybody have any idea, thanks

    Hello,
    The issue is see at the <Q-ENV:Message-Body> we are receiving <?soxtype urn:x-commerceone:document:com:commerceone:XCBL30:XCBL30.sox$1.0?> for OrderResponse header
    You can use java mapping for your requirement. The key is to convert the inputStream into String and then use a find/replace that value and then write to outputStream afterwards.
    Here is a sample code using PI 7.1 API:
    https://wiki.sdn.sap.com/wiki/display/XI/SampleJAVAMappingcodeusingPI7.1+API
    Hope this helps,
    Mark

  • Help with Deserializer XML to Java Object

    Hello,
    I need Deserializer a xml to Object using SAX or another technology
    My code is the follow:
    *          java.io.Writer stringWriter = new StringWriter();*
    *          org.apache.axis.encoding.SerializationContext context0 = new SerializationContext(stringWriter,*
    *                    null);*
    *          javax.xml.namespace.QName qname = new javax.xml.namespace.QName(*
    *                    "http://xxxxxx", "WSUpdateDocumentResponse");*
    *          org.apache.axis.encoding.ser.BeanSerializer serializer = new BeanSerializer(WSUpdateDocumentResponse.class,*
    *                    qname);*
    *          serializer.serialize(qname, null, resp, context0);*
    *          String deserializaXML = stringWriter.toString();*
    The variable deserializaXML contains el XML as String.
    +<ns1:WSUpdateDocumentResponse xmlns:ns1="http://xxxxxxx">+
    +<documentCode xsi:type="xsd:string" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">+
    +43723+
    +</documentCode>+
    +<updateMessageList xsi:type="ns1:ArrayOfWSUpdateMessage" xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>+
    +</ns1:WSUpdateDocumentResponse>+
    That's is ok, but the problem is when, I try The reverse engineering.
    The code is the following:
    *          org.apache.axis.encoding.Deserializer bean = WSUpdateDocumentResponse.getDeserializer(deserializaXML,*
    *                                                                                     WSUpdateDocumentResponse.class,*
    *                                                                                     new javax.xml.namespace.QName("http://xxxxxx, "WSUpdateDocumentResponse"));*
    *          WSUpdateDocumentResponse resp2 = (WSUpdateDocumentResponse)bean.getValue();*
    The object not load correctly, all variables are null.
    Any idea?
    Thanks.
    Regards
    P.D.: The bean WSUpdateDocumentResponse was generated with Axis 1.2RC2, i haven't another option by the dependences project

    Hi,
    Check the methods like getElementById() and getElementByTagName and the corresponding Namespace aware equivalents. Once you have your orders, you can iterate over them and build your target xml.
    Personally, I think your teacher sold you a lemon. This is a job that is best done using XSLT and doing this using dom is like using your bicycle to get to saturn when you have a starship available.
    cheers,
    vidyut

  • My MacBook Pro 13" (2012) is running Windows 7 on Bootcamp and there is an issue with the headset I'm using.

    My MacBook Pro 13" (2012) is running Windows 7 on Bootcamp and there is an issue with the headset I'm using. I use a cheap Logitech Stereo Headset H130, but since there is only on audio plugin on the computer, I purchased a 3.5 mm 4-pin smartphone audio adapter thingy. That allowed me to put both my the sound coming to my headset & the microphone on my headset onto one wire. Everything worked wonderfully when running the Mac OS since they probably have support for that kind of stuff. The problem is though that once I try to use the same method in Windows 7, the OS doesn't recognize my headset microphone at all, but, instead when recording my voice decides to use the built-in mac microphone. Using this adapter still allows me to hear from my headset, but not use the microphone and that becomes a problem. It might be so that Windows 7 doesn't have support\drivers for that... How should I continue from here on out? Any advice?

    From what I have read from others on here you may be out of luck. You would need the appropriate Windows drivers for the Cirrus chip in the Mac and no one has been able to successfully locate them. Apple wouldn't support this since Windows is an optional install.
    Sorry to bring the bad news.

  • Issue with PR conversion to PO using ME59 withqty of similar line items

    Hi All,
    I'm having an issue with PR conversion to PO using ME59
    I have a PR with the following line items with all same details except quantity
    ex 1
    Mat  Qty  Unit Plant   St Loc
    M1   1    EA   P1      S1
    M1   29   EA   P1      S1
    The PR brings in the Unit automatically
    EA is Base Unit Of Measure -Material Master
    BT is Order Unit           -Material Master
    Conversion
    30 EA = 1BT
    When i convert this PR to PO using ME59N then i see 2 lines items
    M1   1   BT
    M2   1   BT
    Its doubling the qty (2 BT = 60 EA)
    ex 2
    Mat  Qty  Unit Plant   St Loc
    M1   1    EA   P1      S1
    M1   2    EA   P1      S1
    M1   27   EA   P1      S1
    The PR brings in the Unit automatically
    EA is Base Unit Of Measure -Material Master
    BT is Order Unit           -Material Master
    Conversion
    30 EA = 1BT
    When i convert this PR to PO using ME59N then i see 2 lines items
    M1   1   BT
    M1   1   BT
    M1   1   BT
    Its 3 times no
    PR Qty = 30 EA
    PO qty = 3  BT = 90 EA
    I guess during conversion to PO
    It sees PR Line item 1 and looks for another line items with similar fields ( in our case it sees line 2 in ex 1 and 2 and 3 in ex 2)
    i adds the qty 1 and 29 in ex1 and converts the total 30 each to 1 BT and when it moves to 2 line it see item1 and again creates 1BT but the line item 2 was already considered and it should be ignored
    Similarly if you see ex2 then it creates 3 limes with 1 BT each
    Let me know how to resolve this issue
    Thanks

    As for std SAP ME59N - make sure there is not rounding value is activated in the Material master as well as info record
    If this is not the case than check any custom code is activated for ME59N
    becuase generally in many compnay when they use ME59n they don't want the same material from diff PR to create the diff line item in the PO so using the custom logic in the user exist they trick the code
    it might be the case for you where you have issue.

  • 3 issues with mapped-superclass

    I created a superclass for my entities which is a simple pojo with 4 properties. I mapped it in JPA with mapped-superclass.
    I want the 'ownerId' and 'created' fields to be read-only on the API, in other words, the pojo shouldn't have setters for those 2 fields.
    TLE objects violently to the absence of those setters. I throws a NPE (see below).
    Secondly, I decided I could live without the read-only requirement, so I put the setters on the pojo, set the mapping's access= to access="FIELD" so that the setters are not called. Out of curiosity, I threw exceptions in the setters just to make sure.
    TLE insists on calling the setters, regardless of the 'access' mode I choose. It's always PROPERTY access which is used. FIELD is ignored.
    So I can live with that too. However once I managed to deploy the whole JPA and started testing it, I realised the prePersist event listener isn't called as it is should be according to the mapping I defined. The prePersist callback is in the mapped-superclass entity mapping and calls a method on the superclass. However it isn't called.
    Does anybody here use mapped-superclass without trouble, or is there an example app out on the net demonstrating its use without issues?
    This is TLE build 58g-fcs, btw.
    Regards
    Adam
    java.lang.NullPointerException
         at oracle.toplink.essentials.internal.ejb.cmp3.metadata.accessors.objects.MetadataMethod.getSetMethodName(MetadataMethod.java:69)
         at oracle.toplink.essentials.internal.ejb.cmp3.metadata.accessors.MetadataAccessor.getSetMethodName(MetadataAccessor.java:330)
         at oracle.toplink.essentials.internal.ejb.cmp3.metadata.accessors.MetadataAccessor.setAccessorMethods(MetadataAccessor.java:575)
         at oracle.toplink.essentials.internal.ejb.cmp3.metadata.accessors.BasicAccessor.processDirectToFieldMapping(BasicAccessor.java:182)
         at oracle.toplink.essentials.internal.ejb.cmp3.metadata.accessors.BasicAccessor.process(BasicAccessor.java:160)
         at oracle.toplink.essentials.internal.ejb.cmp3.metadata.accessors.ClassAccessor.processAccessor(ClassAccessor.java:528)
         at oracle.toplink.essentials.internal.ejb.cmp3.xml.accessors.XMLClassAccessor.processAccessors(XMLClassAccessor.java:371)
         at oracle.toplink.essentials.internal.ejb.cmp3.metadata.accessors.ClassAccessor.processMappedSuperclass(ClassAccessor.java:1128)
         at oracle.toplink.essentials.internal.ejb.cmp3.xml.accessors.XMLMappedSuperclassAccessor.process(XMLMappedSuperclassAccessor.java:67)
         at oracle.toplink.essentials.internal.ejb.cmp3.metadata.accessors.ClassAccessor.processMappedSuperclasses(ClassAccessor.java:1138)
         at oracle.toplink.essentials.internal.ejb.cmp3.metadata.accessors.ClassAccessor.process(ClassAccessor.java:495)
         at oracle.toplink.essentials.internal.ejb.cmp3.xml.accessors.XMLClassAccessor.process(XMLClassAccessor.java:322)
         at oracle.toplink.essentials.internal.ejb.cmp3.metadata.MetadataProcessor.processMappingFile(MetadataProcessor.java:568)
         at oracle.toplink.essentials.internal.ejb.cmp3.metadata.MetadataProcessor.processMappingFiles(MetadataProcessor.java:533)
         at oracle.toplink.essentials.ejb.cmp3.persistence.PersistenceUnitProcessor.processORMetadata(PersistenceUnitProcessor.java:368)
         at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:607)
         at oracle.toplink.essentials.internal.ejb.cmp3.JavaSECMPInitializer.callPredeploy(JavaSECMPInitializer.java:171)
         at oracle.toplink.essentials.internal.ejb.cmp3.JavaSECMPInitializer.initPersistenceUnits(JavaSECMPInitializer.java:239)
         at oracle.toplink.essentials.internal.ejb.cmp3.JavaSECMPInitializer.initialize(JavaSECMPInitializer.java:255)
         at oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider.createEntityManagerFactory(EntityManagerFactoryProvider.java:155)
         at javax.persistence.Persistence.createFactory(Persistence.java:172)

    https://glassfish.dev.java.net/issues/show_bug.cgi?id=4414

  • Read any XML File Elements using SAX Parser in J2se

    Hi All
    I can able to parsed one structured XML file using SAX
    Sample code :
    // ===========================================================
         // SAX DocumentHandler methods
         // ===========================================================
         public void startDocument() throws SAXException {
              logger.info("Start of document");
         public void endDocument() throws SAXException {
              logger.info("End of document");
         public void startElement(String namespaceURI, String localName, // local
                   // name
                   String qualName, // qualified name
                   Attributes attrs) throws SAXException {
              elemName = new String(localName); // element name
              if (elemName.equals(""))
                   elemName = new String(qualName); // namespaceAware = false
              tagPosition = TAG_START;
              // Set the string for accumulating the text in a tag to empty
              elemChars = "";
              // If the element name is "row", create a new row instance
              // If the element is "indexxid", "ModelPrice", or "ModelSpread",
              // the value will be read in the method "characters" and stored.
              if (elemName.equals("row")) {
                   row = new IndexRow();
                   numRows++;
              // logger.info("Number of numRow:"+numRows);
         } // end method startElement
         public void endElement(String namespaceURI, String simpleName, // simple
                   // name
                   String qualName // qualified name
         ) throws SAXException {
              elemName = new String(simpleName);
              if (elemName.equals(""))
                   elemName = new String(qualName); // namespaceAware = false
              tagPosition = TAG_END;
              String indexId = new String();
              Double dblVal = new Double(0);
              // If element name is "row", put the current row in the map for row
              // instances
              if (elemName.equals("row")) {
                   if (numRows <= 5) { logger.info("Row is: " + row.toString()); }
                   //ABX
                   //indexRows.put(row.getIndexxId(), row);
                   if (family.equals("ABX.HE")){
                   indexRows.put(row.getIndexREDId(), row);
                   else {
                        //CDX ITRXX
                             indexRows.put(row.getIndexxId(), row);
              } else if (elemName.equals("IndexID")) {
                   row.setIndexxId(elemChars);
                   // Leave double value at default of zero if there are no chars
                   if (elemChars.trim().length() != 0) {
                        dblVal = new Double(elemChars);
                        row.setCompositeSpread(dblVal);
                        indexId = row.getIndexxId();
              } else if (elemName.equals("REDCode")) {
                   row.setRedCode(elemChars);
              else if (elemName.equals("Name")) {
                   row.setRowName(elemChars);
              } else if (elemName.equals("Series")) {
                   row.setSeries(elemChars);
              } else if (elemName.equals("Version")) {
                   row.setVersion(elemChars);
              } else if (elemName.equals("Term")) {
                   row.setTerm(elemChars);
              } else if (elemName.equals("Maturity")) {
                   row.setMaturity(elemChars);
              } else if (elemName.equals("OnTheRun")) {
                   row.setOnTheRun(elemChars);
              } else if (elemName.equals("Date")) {
                   row.setRowDate(elemChars);
              } else if (elemName.equals("Depth")) {
                   row.setDepth(elemChars);
              else if (elemName.equals("Heat")) {
                   // logger.info("Chars for element " + elemName + " are '" +
                   // elemChars + "'");
                   // Leave double value at default of zero if there are no chars
                   if (elemChars.trim().length() != 0) {
                        dblVal = new Double(elemChars);
                        row.setHeat(dblVal);
                        indexId = row.getIndexxId();
    //          ABX.HE
              else if (elemName.equals("IndexREDId")){
                   row.setIndexREDId(elemChars);
              else if (elemName.equals("Coupon")){
                   row.setCoupon(elemChars);
              if (elemName.equals("Ontherun")) {
                   row.setOnTheRun(elemChars);
         } // end method endElement
         public void characters(char buf[], int offset, int len) throws SAXException {
              // If at end of element, there will be no characters
              if (tagPosition == TAG_END) {
                   return;
              // The characteres method may be called more than once
              // for an element if the internal buffer fills up.
              // Append the characters until the end of the element.
              String strVal = new String(buf, offset, len);
              elemChars = elemChars + strVal;
         } // end method characters
    } // end class MarkItIndexLoader
    but the problem is i want to read (parse) any XML file means any Elemets would be change any time using SAX .In the above example
    else if (elemName.equals("Heat")) {
    else if (elemName.equals("IndexREDId")){
    } else if (elemName.equals("Maturity")) {
    like above I am doing hard code Elements names and reading the values so i don't want hard coding the elements names I want to read any element name and value dynamically.
    If i give any one below XML file i want to read the Elements and displaying to console without changing any code i want to read the XML document.
    EX:
    Student.XML: <root>..</StName>..</StAge>...</root>
    Employee.XML: <root>..</EmpName>..</EmpAge>...</root>
    CdCatalog.XML: <root>..</Cdtitle>...</CdNumber>...</root>
    I need one java program can ready any type of XML file elements and send to the Database table.
    Please any one done like this task please suggest some reference links or books or sample snippet which can help me to develop program in my requirement.
    Thanks in advance
    Regards
    satish

    You should ask in the Java forum.
    Regards
    Stefan

  • 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

  • URGENT: Tomcat, Connection Pool - Issue with web.xml & server.xml

    Folks,
    I am trying to connect to a MS SQL database using Tomcat/JSP but having issues. The code that I am using is as follows:
    Context ic = new InitialContext();
    DataSource ds = (DataSource) ic.lookup("java:comp/env/jdbc/test");
    Connection conn = ds.getConnection();
    Statement stmt = conn.createStatement();
    I have added the following code to my Server.xml:
    <Resource name="jdbc/test" auth="Container" type="javax.sql.DataSource"
    maxActive="100" maxIdle="30" maxWait="10000"
    username="DB_AW_DATA" password="tester" driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver"
    url="jdbc:microsoft:sqlserver://192.168.0.1\\Newcastle"/>
    And the complete web.xml
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE web-app (View Source for full doctype...)>
    - <web-app>
    - <resource-ref>
    <description>Resource reference to java.sql.Connection factory defined in server.xml</description>
    <res-ref-name>jdbc/test</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    </resource-ref>
    </web-app>
    The error message that I am getting is as follows:
    java.sql.SQLException: Cannot load JDBC driver class 'null'
    What confuses me is that I have placed the following files in Tomcat\common\lib...
    mssqlserver.jar
    msbase.jar
    msutil.jar
    I think this is purely an issue with how I configured server.xml and web.xml
    In the Tomcat documentation it states to put the code in the server.xml - but nested inside the Context element. This is something that I have not done as I am clear what the Context should be..
    Can someone assist...
    <Context path="" docBase="ROOT" debug="0"> ???
    what should be the path and the docBase.
    I have deployed the following application:
    http://localhost:8080/SCWAPP/index.jsp
    THANKS IN ADVANCE FOR ALL SUPPORRT

    you should put the code you typed in server.xml into context.xml
    in the META-INF folder and this will fix your problem.
    the latest tomcat docs detail what to do.

  • Performance Issues with large XML (1-1.5MB) files

    Hi,
    I'm using an XML Schema based Object relational storage for my XML documents which are typically 1-1.5 MB in size and having serious performance issues with XPath Query.
    When I do XPath query against an element of SQLType varchar2, I get a good performance. But when I do a similar XPath query against an element of SQLType Collection (Varray of varchar2), I get a very ordinary performance.
    I have also created indexes on extract() and analyzed my XMLType table and indexes, but I have no performance gain. Also, I have tried all sorts of storage options available for Collections ie. Varray's, Nested Tables, IOT's, LOB's, Inline, etc... and all these gave me same bad performance.
    I even tried creating XMLType views based on XPath queries but the performance didn't improve much.
    I guess I'm running out of options and patience as well.;)
    I would appreciate any ideas/suggestions, please help.....
    Thanks;
    Ramakrishna Chinta

    Are you having similar symptoms as I am? http://discussions.apple.com/thread.jspa?threadID=2234792&tstart=0

  • Having a weird issue with my assign after java embedding

    hi,
    I'm having a weird issue with my assign activity, i am using a Java Embedding wherin i access a variable and assign it some data, later in next step when i try to assign some other data to this same variable in assign activity i get a Error message as below.
    com.oracle.bpel.client.BPELFault: faultName: {{http://schemas.xmlsoap.org/ws/2003/03/business-process/}selectionFailure} parts: {{ summary=Invalid to part type. When performing the assign operation, the to node THIS,IS,,TEST is invalid. The node named in the error message was either null or an empty node set, and it was not an instance of org.w3c.Element. Verify the node value at line number 795 is not null and is an instance of org.w3c.Element. } .
    i'm using soa 11.1.1.5
    Can anyone please help ?
    - Thanks
    Shirish

    Shirish,
    It's a bug and you will need to apply a patch for that.
    You can find all explanation in Oracle Support Id ID 1194228.1.
    Arik

  • Safari issues with Tabs, Video, and Java

    Hi.  I updated to Lion and Safari 5.1 and did all the software updates.  I have a MacBook from 2008.  For some reason, I am having a lot of issues with Safari.  I hope someone knows what I am doing wrong.
    1.  Every time I open Safari after I turn on my computer or it wakes up from sleep, I have to do an internet test to get the computer to realize I am still connected to my house WiFi.
    2. The computer goes to sleep after 30 secs.  Can I change this somehow?
    3. I cannot open any videos from YouTube or vidoes my friends have posted on Facebook.
    4. I used to be able to drag a link over an existing tab and it would automatically go there.  Now I have to drag it to the + sign to get it to open.  (command click still works)
    5.  I tried to check my plug-ins to see if that was the problem.  I put all of my internet plug-ins in the trash and added them one by one.  Safari seemed to work a lot faster, but then as soon as it went to sleep, I had the same issues.  Also, I can't find Java anymore (not in my trash, didn't delete anything from the trash) and I did the java test on a website and it's not showing what it's supposed to.  All the software updates say it is fine, but obviously it isn't.
    I know this is a lot of stuff, and most of it is probably due to me not really understanding how my mac works.  I've been looking through the forums to see if anyone else has all of these issues; after an hour and a half of reading discussions, I gave up.  Any advice would be really appreciated.  Thank you.

    So, while waiting for some help, I've been continuing my own research. 
    3. It turned out that it wasn't Java messing with my videos.  I just needed version 10,3,181,34 of Adobe Flash and now all videos are working.   Hope that helps if anyone else was having similar issues.  Here's the link if you need to find out which version you have: http://www.adobe.com/software/flash/about/
    4.  It turns out that there are several other discussions regarding people who can't drag and drop links into Tabs on Safari.  My solution was to write to Apple to ask if they can put that feature back in.
    5. I'm not sure if I am still having Java issues, but so far everything I am needing to upload and watch is fine.
    One and two are still annoying, so I'll continue to look for solutions.  If anyone has any suggestions, I'd appreciate them.  Hope this helps someone as much as it helped me.  I don't want to throw my computer against a wall every 5 seconds now.

  • Wacom, issue with mapping area

    Hello,
    I have:
    Wacon Intuos Pen & Touch, CTH-480/S.
    Wacom driver 6.3.10w2.
    Adobe Photoshop CC 2014.2.1.
    MacBook Pro (late 2013)
    Mac OS X 10.10.1 Yosemite
    I don't have any external monitors
    Most of the times I restart my computer I have to revise the mapping area. Fot "All Others" and for "Adobe Photoshop CC 2014.app".
    I want to use it as:
    Mode: Pen
    Screen Area: Full
    Tablet Area: Portion... (0,0, 4750,7600)
    But after each reset, the tablet works as if I had it set to :
    Mode: Pen
    Screen Area: Portion... (the upper left portion)
    Tablet Area: Portion... (0,0, 4750,7600)
    Notice the screen area set to "Monitor 1" and still the issue:
    Notice the screen area is set to "Full" an still the issue.
    I'm using my tablet with the original provided USB cable. I also tried using another USB port on my computer. I don't have any other device connected to my computer. I have also my Magic Mouse (Apple Bluetooth mouse) turned off. Also I'm using the original provided power source and I also tried using the computer unplugged.
    I had this issue with several older drivers as well.
    This issue started with Mac OS X 10.10 Yosemite. I also tried to fix it, doing a clean install of Yosemite.
    I had tried the "REMOVE" and "RE INSTALL" driver using the "Wacom Tablet Utility".
    I will appreciate your help.
    Kind regards,
           Juan Pedro
    More info:

    Peter,
    Thank you for your reply.
    Your steps does not solve the problem. I had tried those steps several times, but without luck.
    The issue is (I think) because I use a more dense ppi and the driver gets the boot up ppi resolution. I use my screen at "More Space" but when the computer turns on... it on "Best (Retina)".
    So my idea is the driver gets the "Best (Retina)" ppi and when my sessions starts and the computer changes to "More Space"... the Wacom driver already got the other resolution and there is the problem.
    Check this post for more details: Low screen resolution on login after boot | Apple Support Communities
    Miranda,
    The drivers at the UK site and the US site are in the same family.
    The difference is the UK are a bit older than the US.
    For me, the new 6.3.11w3 driver is working a bit better.
    Not perfect, but better.

  • If you are facing issues with AutoVue after upgrading Java

    Oracle periodically releases security updates (CPU see Oracle Critical Patch Update - July 2014 for latest)  for all its software, Java is no exception to it.
    At every CPU, the AutoVue team monitors the impact and documents the steps required to have AutoVue working properly with your integrations
    For your reference, we attach the latest KM note here.  It is a highly recommended reading for customers using AutoVue Client/Server Deployment.
    KM Note 1615032.1 - AutoVue Client Usage with Java 7u51
    (https://support.oracle.com/epmos/faces/DocumentDisplay?id=1615032.1)
    Feel free to post any questions through this Community thread.

    Now, do you have to disconnect your printer everytime that you want to use it? If so, this is just a temporary fix and that's not something that you should have to do with regularity.
    It's GLARING, the amount of people who are having issues with this software. Is APPLE listening to its customers? I'm to the point where I'm about to NOT recommend an I-Pod to anyone that asks. If they do, that's what I'm recommending. I'll also steer them to this website so that they can see with their own eyes, the problems that everyone is having.
    This is totally ridiculous. I've been trying for THREE weeks to get my POS I-Pod Shuffle to download songs through I-Tunes 7.0. It's clear to me that these designers of this software haven't got a clue.
    Sorry for the rant but I've had it with this junk.

Maybe you are looking for

  • Error in PDF Conversion while downloading file from application server

    Hi, I am facing a problem in which i have to download file from application server which is a PDF file (output of SAP Script). I am downloading this file using following code in BSP technology: * event handler for data retrieval EMPCD = REQUEST->GET_

  • Parent Class question

    I have a panel class with a slider on it . pseudocode: public class MyJSlider extends JPanel{ private JSlider myjslider; private Color mycolor; public Color getColor(){return mycolor;} the action taken by the JSlider is to set mycolor to a new Color(

  • Best way to change workstation

    What is the best way to change the workstation name and import it into edirectory. We constantly have user change computer name. Most of the time when we change the computer name it takes day to reflect on the edirectory. When rename the workstation

  • SPAU / SPDD Transport During Upgrade from 4.6C to ECC 6.0

    We are currently upgrading R/3 4.6C to ECC 6.0 SR2. During the DEV upgrade, we performed Dictionary Objects adjustments before ACT 7.00 and SPAU adjustments at the end of the upgrade. All the adjustments are collected in a transport. I read in anothe

  • Animating in After Effects with video footage

    When animating in After Effects, instead of using a solid background, can I use a video as the background and have it playing while the character is moving? I can't see why it wouldn't work. I've saw people question about animating in Flash ect and b