Illegal XML character SAX Parser exception

The element type "body" must be terminated by the matching end-tag "".  i get this exception, its thrown from the SAXParser. if you look at the end tag it shows you an empty string end-tag "". . This should get displayed as end-tag "</body>". instead.
What can i do to make it displayed as end-tag "</body" . There are loads of similar issues on-line, but non of them had a satisfactory answer.
help !

and thanks for the replies :)Most of the replies you thank pointed you at searching how to escape HTML markup when copying the plain text to an HTML document. DId you consider doing this search?
For example, Jakarta's Commons-Lang library has a [StringEscapeUtils class|http://commons.apache.org/lang/api-release/org/apache/commons/lang/StringEscapeUtils.html] with methods that seem to provide just this capability.
now what i think i should do is, to append the auto generated error message with some special characters so it could display in html.No. The "special characters", or merely, special markup, are what makes the browser not render the string correctly (it probably thinks +</body>+ is the closing tag of the similarly-named HTML element. You need to escape this markup, or a at least the lower/greater signs that make it look like markup.
but how can i chnage the auto generated message ?You shouldn't strive to change the message itself, but to convert it to something that renders correctly when embedded into an HTML document.
Edited by: jduprez on Mar 17, 2010 12:35 PM

Similar Messages

  • Illegal XML character exception in Importing data imprt manager

    Did any one of you face Illegal XML character error while importing extracted data from ECC
    I googled and found out XML parser does not like to find '<' '&' in the data , is that true? if so what was the work around ?? BTW we are getting DEBMDM customer data and import manager is bombing with these errors with every other file.
    I know import server is a route , but any other solution?
    -Sudhir

    Hi Sudhir,
    We had faced a similar situation when using extracted Material Master data from ECC.
    We had some special characters in some of the fields like Material description such as (<,^,*,&,#@)etc.But these data were readily imported in MDM without much troubble.However there were some other fields which had error in the Date Formats and were not excepted by MDM
    While automatically importing this data in MDM using the Import server the records failed throwing exceptions.
    We then analysed the Source file carefully in Excel format by using Fillters  and identified these Wrong date charactes which were giving troubble.
    We corrected the dates and had no futher issues for the special character text we imported them with Data type  Text Normalized and they passed corrrectly even with Data type as TEXT.
    So I suggest that you analyses your data correctly in excel if required for better clearance and check for any futher in consisitencies in the dtaa for every field value.
    Hope It Helped,
    Thanks & Regards
    Simona Pinto

  • Deserialization error: XML parsing error: Illegal XML character

    Hi All,
    Anybody knows what caused this? This error occured at the client side when the server returned an object that contains other objects to client during a jaxrpc call. It worked before, something is definitely changed, I reversed my changes but still the same.
    Please help, thanx a lot.
    [java] java.rmi.RemoteException: Runtime exception; nested exception is:
    [java] deserialization error: deserialization error: deserialization error: XML parsing error: com.sun.xml.rpc.sp.ParseException:2: Illegal XML character:
    [java] at com.sun.xml.rpc.client.StreamingSender._send(StreamingSender.java:234)
    [java] at com.ummq.ME_Stub.getMsg(MsgExpertIF_Stub.java:1333)
    [java] at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1764)
    [java] at javax.swing.AbstractButton$ForwardActionEvents.actionPerforme
    d(AbstractButton.java:1817)
    [java] at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:419)
    [java] at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:257)
    [java] at javax.swing.AbstractButton.doClick(AbstractButton.java:289)
    [java] at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1109)
    [java] at javax.swing.plaf.basic.BasicMenuItemUI$MouseInputHandler.mous
    eReleased(BasicMenuItemUI.java:943)
    [java] at java.awt.Component.processMouseEvent(Component.java:5093)
    [java] at java.awt.Component.processEvent(Component.java:4890)
    [java] at java.awt.Container.processEvent(Container.java:1566)
    [java] at java.awt.Component.dispatchEventImpl(Component.java:3598)
    [java] at java.awt.Container.dispatchEventImpl(Container.java:1623)
    [java] at java.awt.Component.dispatchEvent(Component.java:3439)
    [java] at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450)
    [java] at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3165)
    [java] at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
    [java] at java.awt.Container.dispatchEventImpl(Container.java:1609)
    [java] at java.awt.Window.dispatchEventImpl(Window.java:1585)
    [java] at java.awt.Component.dispatchEvent(Component.java:3439)
    [java] at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
    [java] at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:197)
    [java] at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
    [java] at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
    [java] at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
    [java] at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
    [java] Caused by: deserialization error: deserialization error: deserialization error: XML parsing error: com.sun.xml.rpc.sp.ParseException:2: Illegal XML character:
    [java] at com.sun.xml.rpc.encoding.SOAPDeserializationContext.deseriali
    zeMultiRefObjects(SOAPDeserializationContext.java:65)
    [java] before getMsg
    [java] at com.sun.xml.rpc.client.StreamingSender._send(StreamingSender.java:175)
    [java] ... 30 more
    [java] java.rmi.RemoteException: Runtime exception; nested exception is:
    [java] deserialization error: deserialization error: deserialization error: XML parsing error: com.sun.xml.rpc.sp.ParseException:2: Illegal XML character:
    [java] at com.sun.xml.rpc.client.StreamingSender._send(StreamingSender.java:234)
    [java] at javax.swing.JComboBox.fireItemStateChanged(JComboBox.java:1161)
    [java] at javax.swing.JComboBox.selectedItemChanged(JComboBox.java:1218)
    [java] at javax.swing.JComboBox.contentsChanged(JComboBox.java:1265)
    [java] at javax.swing.AbstractListModel.fireContentsChanged(AbstractListModel.java:100)
    [java] at javax.swing.DefaultComboBoxModel.setSelectedItem(DefaultComboBoxModel.java:88)
    [java] at javax.swing.JComboBox.setSelectedItem(JComboBox.java:551)
    [java] at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1764)
    [java] at javax.swing.AbstractButton$ForwardActionEvents.actionPerforme
    d(AbstractButton.java:1817)
    [java] at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:419)
    [java] at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:257)
    [java] at javax.swing.AbstractButton.doClick(AbstractButton.java:289)
    [java] at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1109)
    [java] at javax.swing.plaf.basic.BasicMenuItemUI$MouseInputHandler.mous
    eReleased(BasicMenuItemUI.java:943)
    [java] at java.awt.Component.processMouseEvent(Component.java:5093)
    [java] at java.awt.Component.processEvent(Component.java:4890)
    [java] at java.awt.Container.processEvent(Container.java:1566)
    [java] at java.awt.Component.dispatchEventImpl(Component.java:3598)
    [java] at java.awt.Container.dispatchEventImpl(Container.java:1623)
    [java] at java.awt.Component.dispatchEvent(Component.java:3439)
    [java] at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450)
    [java] at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3165)
    [java] at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
    [java] at java.awt.Container.dispatchEventImpl(Container.java:1609)
    [java] at java.awt.Window.dispatchEventImpl(Window.java:1585)
    [java] at java.awt.Component.dispatchEvent(Component.java:3439)
    [java] at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
    [java] at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:197)
    [java] at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
    [java] at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
    [java] at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
    [java] at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
    [java] Caused by: deserialization error: deserialization error: deserializa
    tion error: XML parsing error: com.sun.xml.rpc.sp.ParseException:2: Illegal XML character:
    [java] at com.sun.xml.rpc.encoding.SOAPDeserializationContext.deseriali
    zeMultiRefObjects(SOAPDeserializationContext.java:65)
    [java] at com.sun.xml.rpc.client.StreamingSender._send(StreamingSender.java:175)
    [java] ... 39 more

    What type of encoding are you using? Do you transform a string in an array of bytes or viceversa?
    Marco

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

  • How to parse XML using SAX Parser sequencially

    I have a requirement to parse XML file sequencially. But I need to stop the parsing in-between for doing some processing.
    Let me explain with example
    I have a file with following structure.
    <InputFile>
    <Invoice>
         <InvoiceNo = "Inv1"/>
    <InvoiceDt = "12012002"/>
    </Invoice>
    <Invoice>
         <InvoiceNo = "Inv2"/>
    <InvoiceDt = "12012002"/>
    </Invoice>
    <Invoice>
         <InvoiceNo = "Inv3"/>
    <InvoiceDt = "12012002"/>
    </Invoice>
    For each Invoice node I need to process some activites. So I need to write a method which will open the XML file and parse and returns me a complete element from <invoice> to </Invoice> sequencially.
    Please let me know whther some body has solution for this.
    Manoj.

    If you're using a SAX parser then you can implement your code in the startElement(), endElement(), and characters() methods... have a look at the tutorial here:
    http://java.sun.com/xml/jaxp/dist/1.1/docs/tutorial/index.html

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

  • SAX Parser exception in the reciever channel

    Hi Experts,
    We are using file to mail scenario in which we are using java mappings to handle the EDI files sent to the third party system.
    Currenly we have got SAX exception in the reciever communication channel.
    The sender communication channel has executed successfully.
    Please find below the error at the reciever channel:
    "failed to send mail: com.sap.aii.messaging.util.XMLScanException: java.lang.NullPointerException; nested exception caused by: com.sap.engine.lib.xml.parser.NestedSAXParserException: Fatal Error: com.sap.engine.lib.xml.parser.ParserException: Name expected: 0x32(:main:, row:1, col:106)(:main:, row=1, col=106) -> com.sap.engine.lib.xml.parser.ParserException: Name expected: 0x32(:main:, row:1, col:106)"
    Please suggest whether the above error is related to the BASIS settings of the server or it is related to XI reciever channel settings.
    Thanks and Regards,
    Srikanth.

    Hi Srikanth,
    Tell us how the output payload looks like?? if you have used mail package xsd, then payload shoudl go to the Content of it.. Are you taking care of this??
    Also if possible can you paste here the payload which you are getting after the operation mapping .
    Regards
    Suraj

  • Problem reading ' from XML uisng SAX Parser

    Hi All,
    I have a XML which contains the following element
    <DataText>This is simple ' Text</DataText>I have included & apos ; in the element called DataText.
    When parsing the element, am getting only the text that appears before & apos ;
    When Not including & apos ; am able to get the full text from this element.
    I observed that in the method characters(char buf[], int offset, int len)
    Thelen attribute shows the total length from start position to the position where & apos ; starts...
    How can i get the whole text which includes even " & apos ; "
    Thanks
    Note : while posting this request, & apos; is being formatted to ' . thats the reason included space between them

    HI,
    Was not doing much in the characters method, anyway here is the code
    public void characters(char buf[], int offset, int len) throws SAXException{
        elementText  = new String(buf, offset, len).trim();
    }The value for len is from the start position of the element value and the start position of the ' & apos; ' in the XML File...
    If i remove the ' & apos; ' in the element value , then the len is the full character length in between the element.
    Very confused why this is happening !!
    Did anyone face this problem ever before ?

  • SAX parser exception : Namespace not supported by SAX parser

    Hi,
    I'm using xslt to transform xml to html. I've downloaded Xalan2J from Apache website and I've used Transformer factory implementation.
    The code works fine through Forte IDE environment where I've mounted jar files xerces.jar, xml-apis.jar, xalan.jar
    The problem occurs when I try to instantiate the same method through JSP page. It throws an exception
    SAXParser exception : Namespace not supported by SAXParser. I'm trying to run the jsp file through jakarta tomcat environment.
    I've included xerces.jar, xml-apis.jar, xalan.jar in my classpath. I fail to understand why namespace support is not available.
    Any help/suggetsions would be appreciated :)
    Thanks

    Hi,
    Yes, In tomcat environment, by default the jar files in the lib directory are set before reading the system classpath which causes a problem. One could replace the xerces.jar with a new jar file and delete parser.jar but that has its own set of problems.
    The other alternative would be to use something like
    System.setProperty("javax.xml.parsers.SAXParserFactory","org.apache.xerces.jaxp.SAXParserFactoryImpl");
    This worked for me..:)

  • XML - SAX Parsing Question

    Hi,
    I am parsing XML using SAX parser and fill the values into the HashTable ( like Key value pair ).. so i can get the vaues for a particular key using hash get function.
    For the following XML. There are 2 "subscriberNumber" attribute, one is under "sn:Subscriber" and the another is under "sn:SubscriberChange".
    I can able to put this values in hash table and when i print the Hash table it is printing as sn:subscriberNumber=[1234567890, 1234567890] .. But how will i know which one is from "sn:Subscriber" and which is from "sn:SubscriberChange"
    This is the XML :
    <sn:SubscriberNotification>
    <sn:notificationSubType>1120</sn:notificationSubType>
    <sn:Subscriber>
         <cng:PaymentType>PostPaid</cng:PaymentType>
         <sn:subscriberNumber>1234567890</sn:subscriberNumber>
    </sn:Subscriber>
    <sn:SubscriberChange>
         <sn:subscriberNumber>1234567890</sn:subscriberNumber>
    </sn:SubscriberChange>
    </sn:SubscriberNotification>
    Any suggestion and pointers are really helpful
    Thanks,
    -Raj..

    Try something like this:
    import java.util.Stack;
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;
    class MyHandler extends DefaultHandler {
        Stack openTags = new Stack();
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            if (qName.equals("sn:subscriberNumber")) {
                String parentTag = (String)openTags.peek();
                System.out.println("Parent tag of this <sn:subscriberNumber> is : <" + parentTag + ">");
            openTags.push(qName);
        public void endElement(String uri, String localName, String qName) throws SAXException {
            openTags.pop();
    }Regards

  • Parsing the large XML ( 1GB) using SAX PARSER

    We have very large XMLs being generated by processes. These XMLs should be validated first and then parsed next. We have implementation that works for small files. My question is
    how can we validate and parse large XMLs with SAX parser?

    The same way as parsing a small XML file, no? Why don't you try it? Then if you have problems that you can't solve, ask about them here.

  • Invalid XML Character from Jarred file

    I have a server class that attempts to load an XML file and parse the same.
    The entire code works fine when the class is extracted and parses correctly. However, when
    a distribution jar is created, the extraction of the XML file fails with an invalid character
    exception.
    124.0.24,5,RMI Runtime]
    10/15/04 3:31:59 PM user=server stackTrace=org.xml.sax.SAXParseException: Illegal XML character:  &#x0;.
            at org.apache.crimson.parser.InputEntity.fatal(InputEntity.java:1100)
            at org.apache.crimson.parser.InputEntity.getc(InputEntity.java:360)
            at org.apache.crimson.parser.Parser2.getc(Parser2.java:3166)
            at org.apache.crimson.parser.Parser2.maybeComment(Parser2.java:1042)
            at org.apache.crimson.parser.Parser2.content(Parser2.java:1935)
            at org.apache.crimson.parser.Parser2.maybeElement(Parser2.java:1654)Why this is happening I have no clue. The XML file in the jar is the same as the
    XML file in the un-jarred directory. Any assistance would be appreciated in advance :-).
    InputStream inStream = null;
            try {
                inStream = this.getClass().getResourceAsStream(
                        "/global/service/admin/" + "test-resource.xml");
                byte arr[] = new byte[inStream.available()];
                inStream.read(arr);
                inStream.close();
                String cfg = new String(arr);
                Document doc = null;
                DocumentBuilderFactory docFactory
                    = DocumentBuilderFactory.newInstance();
                DocumentBuilder parser = docFactory.newDocumentBuilder();                 
                doc = parser.parse(new InputSource(new StringReader(cfg)));
                handleDocument(doc);
            } catch (Exception exp) {
                Log.error(exp);
            } finally {
                if (inStream != null) {
                    try {
                        inStream.close();
                    } catch (IOException e) {
            }Thanks in advance

    Thanks for the input. Once I changed the code to directly use input stream, it worked like a charm even from the jar file.
    While experimenting, I found the following:
    <foos>
           <foo> test</foo>
           <foo>test2</foo>
    </foos>If the line between the two foo elements were removed, the jar one worked with my original code. However, with the input stream it seems to not care. I had build the XML file on a Solaris box using 'vi' and the application was also run from solaris.

  • Sax parser returned an exception. Message: Invalid character (Unicode: 0x12

    Hi,
    I'm getting the error 'Sax parser returned an exception. Message: Invalid character (Unicode: 0x12), Entity publicId: , Entity systemId: , Line number: 47, Column number: 75'
    when I try and run a report in BI Answers 10g.
    Apparently it's to do with a Java applet (or piece of Java code anyway) not being sent to an exception so it can't handle it. The problem is that I can't
    run the report to get at some of the views that seem only available at run time. eg. charts.
    Does anyone know how I can see behind the scenes of views without running the report?
    Or does anyone know how to get rid of this error anyway?
    Many thanks,
    - Jenny

    Hi Satya,
    I am facing the same issue. but I am facing this issue with Mozilla Firefox browser only. If I modify same reports in internet explorer I don't get this error.  It seems this issue is with OBIEE 10g version only and Oracle has provided some patches on this in OBIEE 11g .
    You have posted this question long back. If you have got any solution for this then please let me know also.
    Thanks

  • Sax Parser for loading XML file

    We have a requirment by which we need to load huge XMl file in our DB everyday.
    THe XML file format is like --
    <?xml version="1.0" encoding="UTF-8"?>
    <root>
    <emp>
    <ename>aaa</ename>
    <sal>3000</sal>
    </emp>
    <emp>
    <ename>bbb</ename>
    <sal>5000</sal>
    </emp>
    <dept>
    <name>productiong</name>
    <location>USA</location>
    <dept>
    I have written XMl SAX parser to load this file into DB -
    import org.xml.sax.helpers.DefaultHandler;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.XMLReader;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.xml.sax.Attributes;
    import java.io.*;
    import java.sql.*;
    import oracle.jdbc.driver.*;
    import oracle.xml.sql.*;
    import oracle.sql.*;
    import oracle.jdbc.*;
    import oracle.jdbc.pool.OracleDataSource;
    import java.util.*;
    public class test extends DefaultHandler
    String thisElement="";
    String table_name="";
    String table_name_2="";
    String sql="";
    String value_clause="";
    StringBuffer value_clauseBuffer;
    String Insert_sql="";
    int flag;
    String columnNames="";
    String questionmarks="";
    static String conStr = "jdbc:oracle:thin:@abcd1234:1521:dss501";
    static Connection conn;
    String arrayValues[] = new String[30];
    int j = 0;
    int emptyElementFlag = 0;
    public SurveyReader() throws SQLException, FileNotFoundException, IOException{
    DBConnect("username", "password");
    public static void DBConnect(String username, String password)
    throws SQLException, FileNotFoundException, IOException {
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    conn = DriverManager.getConnection(conStr, username, password);
    conn.setAutoCommit(true);
    public void startElement(String namespaceURI, String localName,
    String qName, Attributes atts) throws SAXException {
    thisElement = qName;
    if (thisElement!=table_name){
    columnNames = columnNames + ", " + qName;
    questionmarks = questionmarks +", " + "?";
    emptyElementFlag =0;
    public void characters(char[] ch, int start, int length)
    throws SAXException {
    if (thisElement !="root"){     
    if ((length == 0) && (thisElement !="") ){
    table_name = thisElement;
    sql = " Insert into "+ table_name +"(";
    value_clause="";
    value_clauseBuffer =null;
    columnNames = "";
    questionmarks ="";
    j =0;
    if ((length != 0) && (thisElement!="") && (thisElement!=table_name)){
    emptyElementFlag = 1;
    String s = new String(ch, start, length);
    String newString = s.replaceAll("'", "''");
    // String newString = s;
    if (value_clauseBuffer== null){
    value_clauseBuffer = new StringBuffer(newString);
    else{
    value_clauseBuffer.append(newString);
    public void endElement(String namespaceURI, String localName, String qName)
    throws SAXException {
    if (thisElement !="root"){
    if ((!(value_clauseBuffer == null))||((emptyElementFlag ==0) && (qName !=table_name))) {
    try{
    //value_clauseBuffer.append("', '");
    if (value_clauseBuffer == null){
    arrayValues[j]="";
    else{
    arrayValues[j]=""+value_clauseBuffer;
    j = j+1;
    value_clauseBuffer = null;
    emptyElementFlag =0;
    }catch(Exception e){
    System.err.println(e);
    System.exit(2);
    if (qName == table_name){
    if (!(value_clauseBuffer == null)){
    value_clause = "'"+value_clauseBuffer;
    columnNames =columnNames.substring(1, columnNames.length());
    int paramNumber = j;
    questionmarks =questionmarks.substring(1, questionmarks.length());
    sql = sql + columnNames + " ) values (" + questionmarks +"); ";
    Insert_sql=Insert_sql + sql;
    sql = "Begin "+sql + " End; ";
         try{
         PreparedStatement pstat = conn.prepareStatement(sql);
    for (int i=0; i<=j-1; i++ ){
    int k = i+1;
    pstat.setObject(k, arrayValues);
         ResultSet rset = pstat.executeQuery();
         rset.close();
         pstat.close();
    catch (Exception e) {
    System.err.println(e);
    System.out.print("sql " + sql);
    System.exit(1);
    table_name_2 = table_name;
    thisElement = "";
    public static void main (String args[]) {
    XMLReader xmlReader = null;
    System.out.println("Time " + new java.util.Date());
    try {
    SAXParserFactory spfactory = SAXParserFactory.newInstance();
    spfactory.setValidating(false);
    SAXParser saxParser = spfactory.newSAXParser();
    xmlReader = saxParser.getXMLReader();
    xmlReader.setContentHandler(new SurveyReader());
    xmlReader.setErrorHandler(new SurveyReader());
    InputSource source = new InputSource("short.xml");
    xmlReader.parse(source);
    conn.close();
    } catch (Exception e) {
    System.err.println(e);
    System.exit(1);
    This parser takes 2 hours to laod file of size around 8MB.
    ANy suggestions on improving performance of the parser.
    ANy other approach I should be taking to load this file into DB.
    We are using ORacle 9i DB with Character set UTF 8.
    Thanks!

    String buf = (new String(ch, start, length)).trim();
    if (thisElement != "root"){   
    if ((buf.length() == 0) && (thisElement !="") ){
    It run ok!
    Thanks 58871!
    Now, i want to export oracle table to xml file like :
    <?xml version="1.0" encoding="UTF-8"?>
    <root>
    <emp>
    <ename>aaa</ename>
    <sal>3000</sal>
    </emp>
    <emp>
    <ename>bbb</ename>
    <sal>5000</sal>
    </emp>
    </root>
    Can SAX export to xml format?
    Pham Thanh Tung

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

Maybe you are looking for