FWIW, after making the changes mentioned earlier so it would work better with MySQL, I've also modified it so it uses XMLStreamWriter, allowing it to process larger files. Here's the updated Dbsql2xml.java file containing the changes for both MySQL and XMLStreamWriter:
*The"dbsql2xml"isJavatool(class)fortransforming(export)relationaldatabasesintohierarchicalXML.Copyright(C)*2005�2006StepanRybarThislibraryisfreesoftware;youcanredistributeitand/ormodifyitunderthetermsoftheGNU*LesserGeneralPublicLicenseaspublishedbytheFreeSoftwareFoundation;eitherversion2.1oftheLicense,or(atyour*option)anylaterversion.Thislibraryisdistributedinthehopethatitwillbeuseful,butWITHOUTANYWARRANTY;without*eventheimpliedwarrantyofMERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNULesserGeneralPublicLicense*formoredetails.YoushouldhavereceivedacopyoftheGNULesserGeneralPublicLicensealongwiththislibrary;ifnot,*writetotheFreeSoftwareFoundation,Inc.,59TemplePlace,Suite330,Boston,MA02111-1307USAFormoreinformation,see*http://sourceforge.net/projects/dbsql2xml/StepanRYBARModra6Stodulky1979PrahatheCzechRepublicxrybs01@seznam.cz*http://sourceforge.net/projects/dbsql2xml/*/packagenet.sf.dbsql2xml;importjava.io.ByteArrayOutputStream;importjava.io.File;importjava.io.OutputStream;importjava.io.FileOutputStream;importjava.io.ByteArrayOutputStream;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.ResultSetMetaData;importjava.sql.Statement;importjava.text.SimpleDateFormat;importjava.util.ArrayList;importjava.util.Date;importjava.util.HashMap;importjava.util.Iterator;importjava.util.Set;importjava.util.Vector;importjavax.xml.parsers.DocumentBuilder;importjavax.xml.parsers.DocumentBuilderFactory;importjavax.xml.stream.XMLOutputFactory;importjavax.xml.stream.XMLStreamWriter;importorg.apache.commons.logging.Log;importorg.apache.commons.logging.LogFactory;importorg.w3c.dom.Document;importorg.w3c.dom.Element;importorg.w3c.dom.Node;importorg.w3c.dom.NodeList;importorg.w3c.dom.ProcessingInstruction;importorg.w3c.dom.Text;/***<code>dbsql2xml</code><br/>*"dbsql2xml"isJavatool(class)fortransformation(export,convert)*relationaldatabaseintohierarchicalXML.ItrequiresJRE5.0,JDBCandSQL*DBMS."dbsql2xml"usesXMLdocumentformappingdatabasetablesandcolumns*intoelementsoftreeXML.<br/>*Formoreinformationsee"https://sourceforge.net/projects/dbsql2xml/".**@version0.212006-01-08-modifiedbyDallanQuass2010-02-02*/publicclassDbsql2xml{privateLoglog=LogFactory.getLog(Dbsql2xml.class);privatebooleanconnnectionPassed=true;privateStringapplicationInfo=null;privateStringpathToMappingXmlFile=null;privateStringpathToXsdFile=null;privateStringnamesOfGlobalVariables=null;privateStringvaluesOfGlobalVariables=null;privateStringpathToOutputXmlFile=null;privateStringglobalCharsetName=null;privateHashMapglobalVariables=newHashMap();privateConnectionconnection=null;privateStatementglobalStatement=null;privateXPathHelperxPathHelper=newXPathHelper();privateXMLStreamWriterwriter=null;privatebooleanmultiStatementDriver=true;privatelongtotalTime=0;privatelongxmlTime=0;privateStringjdbcDriver=null;privateStringjdbcURL=null;privateStringjdbcUserName=null;privateStringjdbcPassword=null;privateStringconnUrl=null;/***Createsa<code>dbsql2xml</code>foroutputto<code>File</code>.**@parampathToMappingXmlFile*e.g"treeXMLMapping.xml"*@parampathToXsdFile*e.g."dbsql2xml.xsd"*@paramnamesOfGlobalVariables*e.g."$gvG01#$gvG02#$gvG03"or"myVarX#myVarY#myVarZ"*@paramvaluesOfGlobalVariables*e.f"01#John Smith#2005-05-10"*@parampathToOutputXmlFile*e.g"treeXMLOut.xml"<br/>*<br/>*token,whichdelimitesnamesandvaluesofglobalvariables,is*setinmappingXMLfileinsideelement*<code>tokenForCommandLineStringArrays</code><br/>*itcanbesingleormultiplecharacter<br/>*tokenisthesamefornamesandvaluesofglobalvariables<br/>*<br/>*Soexampleofcreating<code>dbsql2xml</code>objectis:<br/>*<code>dbsql2xmlmyDbSql2Xml=newdbsql2xml("treeXMLMapping.xml","dbsql2xml.xsd","$gvG01","001","treeXMLOut.xml");</code>*<br/>*Seeexampleindistribution(standaloneapplicationandservlet).*/publicDbsql2xml(StringpathToMappingXmlFile,StringpathToXsdFile,StringnamesOfGlobalVariables,StringvaluesOfGlobalVariables,StringpathToOutputXmlFile){this.pathToMappingXmlFile=pathToMappingXmlFile;this.pathToXsdFile=pathToXsdFile;this.namesOfGlobalVariables=namesOfGlobalVariables;this.valuesOfGlobalVariables=valuesOfGlobalVariables;this.pathToOutputXmlFile=pathToOutputXmlFile;this.connection=null;this.connnectionPassed=false;log.debug("Creating Dbsql2xml with: "+"\npathToMappingXmlFile = "+pathToMappingXmlFile+"\npathToXsdFile = "+pathToXsdFile+"\nnamesOfGlobalVariables = "+namesOfGlobalVariables+"\nvaluesOfGlobalVariables = "+valuesOfGlobalVariables+"\npathToOutputXmlFile = "+pathToOutputXmlFile);}publicDbsql2xml(StringpathToMappingXmlFile,StringpathToXsdFile,StringnamesOfGlobalVariables,StringvaluesOfGlobalVariables,StringpathToOutputXmlFile,Connectioncon){this.pathToMappingXmlFile=pathToMappingXmlFile;this.pathToXsdFile=pathToXsdFile;this.namesOfGlobalVariables=namesOfGlobalVariables;this.valuesOfGlobalVariables=valuesOfGlobalVariables;this.pathToOutputXmlFile=pathToOutputXmlFile;this.connection=con;log.debug("Creating Dbsql2xml with: "+"\npathToMappingXmlFile = "+pathToMappingXmlFile+"\npathToXsdFile = "+pathToXsdFile+"\nnamesOfGlobalVariables = "+namesOfGlobalVariables+"\nvaluesOfGlobalVariables = "+valuesOfGlobalVariables+"\npathToOutputXmlFile = "+pathToOutputXmlFile);}/***Createsa<code>dbsql2xml</code>foroutputto<code>String</code>,*<code>Document</code>and<code>System.out</code>.**@parampathToMappingXmlFile*e.g"treeXMLMapping.xml"*@parampathToXsdFile*e.g."dbsql2xml.xsd"*@paramnamesOfGlobalVariables*e.g."$gvG01#$gvG02#$gvG03"or"myVarX#myVarY#myVarZ"*@paramvaluesOfGlobalVariables*e.f"01#John Smith#2005-05-10"<br/>*<br/>*token,whichdelimitesnamesandvaluesofglobalvariables,is*setinmappingXMLfileinsideelement*<code>tokenForCommandLineStringArrays</code><br/>*itcanbesingleormultiplecharacter<br/>*tokenisthesamefornamesandvaluesofglobalvariables<br/>*<br/>*Soexampleofcreating<code>dbsql2xml</code>objectis:<br/>*<code>dbsql2xmlmyDbSql2Xml=newdbsql2xml("treeXMLMapping.xml","dbsql2xml.xsd","$gvG01","001");</code>*<br/>*Seeexampleindistribution(standaloneapplicationandservlet).*/publicDbsql2xml(StringpathToMappingXmlFile,StringpathToXsdFile,StringnamesOfGlobalVariables,StringvaluesOfGlobalVariables){this.pathToMappingXmlFile=pathToMappingXmlFile;this.pathToXsdFile=pathToXsdFile;this.namesOfGlobalVariables=namesOfGlobalVariables;this.valuesOfGlobalVariables=valuesOfGlobalVariables;this.pathToOutputXmlFile=null;this.connection=null;this.connnectionPassed=false;log.debug("Creating Dbsql2xml with: "+"\npathToMappingXmlFile = "+pathToMappingXmlFile+"\npathToXsdFile = "+pathToXsdFile+"\nnamesOfGlobalVariables = "+namesOfGlobalVariables+"\nvaluesOfGlobalVariables = "+valuesOfGlobalVariables+"\npathToOutputXmlFile = "+pathToOutputXmlFile);}/***Createsa<code>dbsql2xml</code>foroutputto<code>String</code>,*<code>Document</code>and<code>System.out</code>with*<code>Connection</code>alreadydefined.**@parampathToMappingXmlFile*e.g"treeXMLMapping.xml"*@parampathToXsdFile*e.g."dbsql2xml.xsd"*@paramnamesOfGlobalVariables*e.g."$gvG01#$gvG02#$gvG03"or"myVarX#myVarY#myVarZ"*@paramvaluesOfGlobalVariables*e.g."01#John Smith#2005-05-10"*@paramconnection*<br/>*<br/>*token,whichdelimitesnamesandvaluesofglobalvariables,is*setinmappingXMLfileinsideelement*<code>tokenForCommandLineStringArrays</code><br/>*itcanbesingleormultiplecharacter<br/>*tokenisthesamefornamesandvaluesofglobalvariables<br/>*<br/>*Soexampleofcreating<code>dbsql2xml</code>objectis:<br/>*<code>dbsql2xmlmyDbSql2Xml=newdbsql2xml("treeXMLMapping.xml","dbsql2xml.xsd","$gvG01","001");</code>*<br/>*Seeexampleindistribution(standaloneapplicationandservlet).*/publicDbsql2xml(StringpathToMappingXmlFile,StringpathToXsdFile,StringnamesOfGlobalVariables,StringvaluesOfGlobalVariables,Connectionconnection)throwsException{this.pathToMappingXmlFile=pathToMappingXmlFile;this.pathToXsdFile=pathToXsdFile;this.namesOfGlobalVariables=namesOfGlobalVariables;this.valuesOfGlobalVariables=valuesOfGlobalVariables;this.pathToOutputXmlFile=null;this.connection=connection;log.debug("Creating Dbsql2xml with: "+"\npathToMappingXmlFile = "+pathToMappingXmlFile+"\npathToXsdFile = "+pathToXsdFile+"\nnamesOfGlobalVariables = "+namesOfGlobalVariables+"\nvaluesOfGlobalVariables = "+valuesOfGlobalVariables+"\npathToOutputXmlFile = "+pathToOutputXmlFile);}privatevoiddoExport(OutputStreamout){longstartTime=System.currentTimeMillis();try{checkInputParameters();//loadmapping(configuration)XMLfileDocumentmapping=createMappingFromFile();//initializeXPathforfutureusexPathHelper=newXPathHelper();//loadglobalvariablesfromconstructorsparametersandmappingXMLfileloadGlobalVariables(namesOfGlobalVariables,valuesOfGlobalVariables,mapping);//createoutputXMLwriterwriter=XMLOutputFactory.newInstance().createXMLStreamWriter(out);writer.writeStartDocument();//createrootelementofoutputXMLdocumentStringrootElementName=xPathHelper.getString("config/rootElementName",mapping);if(rootElementName==null||rootElementName.trim().length()==0){rootElementName="dbsql2xml";}writer.writeStartElement(rootElementName);applicationInfo=initApplicationInfo();writer.writeComment(applicationInfo);globalCharsetName=xPathHelper.getString("config/globalCharsetName",mapping);if(connection==null){if(jdbcDriver==null||jdbcURL==null||jdbcUserName==null||jdbcPassword==null){jdbcDriver=xPathHelper.getString("config/connectionProperties/jdbcDriver",mapping);jdbcURL=xPathHelper.getString("config/connectionProperties/jdbcURL",mapping);jdbcUserName=xPathHelper.getString("config/connectionProperties/jdbcUserName",mapping);jdbcPassword=xPathHelper.getString("config/connectionProperties/jdbcPassword",mapping);}connection=getConnection(jdbcDriver,jdbcURL,jdbcUserName,jdbcPassword);}multiStatementDriver=xPathHelper.getString("config/connectionProperties/multiStatementDriver",mapping).equalsIgnoreCase("true");//loaddatafromdatabasetohierarchicalXMLdocumentElementtopLevelTableElement=xPathHelper.getElement("/config/table",mapping);processTableElement(topLevelTableElement);//endXMLdocumentwriter.writeEndElement();writer.writeEndDocument();writer.flush();writer.close();//appendtoorprocessoutputXMLdocumentXSLTorCSS(ifany)in//mappingfile//broken-we'd need to write the document to a byte array, then convert the byte array to a Document before calling this function//ElementprocessingInstructionsElement=xPathHelper.getElement("config/processingInstructions",mapping);//doProcessingInstructions(processingInstructionsElement,rootElement);//Ifwedidn't get a connection from the client then close it.if(!this.connnectionPassed){connection.close();connection=null;}}catch(Exceptione){log.error("Error!",e);}finally{System.gc();}log.debug("It took "+(System.currentTimeMillis()-startTime)+" ms to create the xml");xmlTime+=(System.currentTimeMillis()-startTime);}privateStringinitApplicationInfo(){StringretVal="";retVal="The \"dbsql2xml\" is Java tool (class) for transforming (export) relational databases into hierarchical XML.\nFor more information, see http://sourceforge.net/projects/dbsql2xml/.\n"+"It has been modified by Dallan Quass to work for very large documents and MySQL";returnretVal;}privatevoidcheckInputParameters()throwsException{try{if(pathToMappingXmlFile==null|pathToMappingXmlFile==""){thrownewException("No mapping XML file specified.");}if(pathToXsdFile==null|pathToXsdFile==""){thrownewException("No XML Schema specified.");}if(namesOfGlobalVariables==null|valuesOfGlobalVariables==null){namesOfGlobalVariables="";valuesOfGlobalVariables="";}}catch(Exceptione){log.error("pathToMappingXmlFile=\""+pathToMappingXmlFile+"\", pathToXsdFile=\""+pathToXsdFile+"\", namesOfGlobalVariables=\""+namesOfGlobalVariables+"\", valuesOfGlobalVariables=\""+valuesOfGlobalVariables+"\"");log.error("error in checkInputParameters");throwe;}}/***Outputresultsto<code>File</code>.Itisintendedforstandalone*export(transformation,extraction)application.Outputencodingisin*UTF-8.*/publicvoiddoExportIntoFile()throwsException{try{if(pathToOutputXmlFile==null|pathToOutputXmlFile==""){thrownewException("It looks like not four parameters was given - no file for output");}else{longstartTime=System.currentTimeMillis();OutputStreamout=newFileOutputStream(pathToOutputXmlFile);doExport(out);out.close();//TransformerFactorytransformerFactory=TransformerFactory.newInstance();//Transformertransformer=transformerFactory.newTransformer();//Sourcesource=newDOMSource(outDocument);//StreamResultstreamResult=newStreamResult(newFile(pathToOutputXmlFile));//transformer.transform(source,streamResult);log.debug("Wrote file to "+pathToOutputXmlFile);log.debug("It took "+(System.currentTimeMillis()-startTime)+" ms to process the xml");totalTime+=(System.currentTimeMillis()-startTime);}}catch(Exceptione){log.error("error in doExportIntoFile",e);throwe;}}/***Outputresultsto<code>String</code>.ItisintendedforJavaservlets.*OutputencodingisinUTF-8.*/publicStringdoExportIntoString()throwsException{try{ByteArrayOutputStreambyteArrayOutputStream=newByteArrayOutputStream();doExport(byteArrayOutputStream);//TransformerFactorytransformerFactory=TransformerFactory.newInstance();//Transformertransformer=transformerFactory.newTransformer();//Sourcesource=newDOMSource(outDocument);//StreamResultstreamResult=newStreamResult(byteArrayOutputStream);//transformer.transform(source,streamResult);returnbyteArrayOutputStream.toString("UTF-8");//outputisalwaysin//UTF-8}catch(Exceptione){log.error("error in doExportIntoString",e);throwe;}}/***Outputresultsto<code>System.out</code>.Itisintendedfordebugging*purposesonsystemswithconsole.OutputencodingisinUTF-8.*/publicvoiddoExportIntoStandardOutput()throwsException{try{System.out.println(doExportIntoString());}catch(Exceptione){log.error("error in doExportIntoStandardOutput",e);throwe;}}/***Outputresultsto<code>Document</code>.Itisintendedforapplication*integrationintootherXMLrelatedones.OutputencodingisinUTF-8.*///broken-weneedtowritethedocumenttoabytearray,thenconvertthebytearraytoaDocument//publicDocumentdoExportIntoDocument()throwsException{//try{//doExport();//return(outDocument);//}//catch(Exceptione){//log.error("error in doExportIntoString",e);//throwe;//}//}privatevoidloadGlobalVariables(StringnamesOfGlobalVariables,StringvaluesOfGlobalVariables,Documentdocument)throwsException{try{//loadglobalvariablesgivenbymappingfileNodeListnodeList=xPathHelper.getNodeList("config/globalVariables/globalVariable",document);for(inti=0;i<nodeList.getLength();i++){globalVariables.put(xPathHelper.getString("@name",(Node)nodeList.item(i)),xPathHelper.getString("self::node()",(Node)nodeList.item(i)));}//loadglobalvariablesgivenbyconstructorStringtoken=xPathHelper.getString("config/tokenForCommandLineStringArrays",document);String[]globalVariablesNames=namesOfGlobalVariables.split(token);String[]globalVariablesValues=valuesOfGlobalVariables.split(token);if(globalVariablesNames.length==globalVariablesValues.length){for(inti=0;i<globalVariablesNames.length;i++){globalVariables.put(globalVariablesNames[i],globalVariablesValues[i]);//global//variables//is//HashMap}}else{thrownewException("Constructor parameters global variables names and values does not match in count.");}}catch(Exceptione){log.error("error in loadGlobalVariables",e);throwe;}}privateDocumentcreateMappingFromFile()throwsException{//pathtofileis//globalStringJAXP_SCHEMA_LANGUAGE="http://java.sun.com/xml/jaxp/properties/schemaLanguage";StringW3C_XML_SCHEMA="http://www.w3.org/2001/XMLSchema";StringJAXP_SCHEMA_SOURCE="http://java.sun.com/xml/jaxp/properties/schemaSource";try{DocumentBuilderFactorydocumentBuilderFactory=DocumentBuilderFactory.newInstance();//validateagainstXMLSchemaindbsql2xml.xsddocumentBuilderFactory.setNamespaceAware(true);Stringversion=System.getProperty("java.version");//Essentiallymakesurewearejdk1.5orabovetodothespecialstuff.if(isJaxpIncluded(version)){documentBuilderFactory.setValidating(false);//mappingfilewillbevalidatedagainstdefinitioninXMLSchemaUnfortunatelysaxondoesn't support this. BEWAREdocumentBuilderFactory.setXIncludeAware(true);//mappingfilecanuseXIncludedocumentBuilderFactory.setAttribute(JAXP_SCHEMA_LANGUAGE,W3C_XML_SCHEMA);documentBuilderFactory.setAttribute(JAXP_SCHEMA_SOURCE,newFile(pathToXsdFile));}DocumentBuilderdocumentBuilder=documentBuilderFactory.newDocumentBuilder();Documentdocument=documentBuilder.parse(newFile(pathToMappingXmlFile));returndocument;}catch(Exceptione){e.printStackTrace();log.error("error in createDocumentFromFile",e);throwe;}}//privateDocumentcreateNewDocument()throwsException{//try{//DocumentBuilderFactorydocumentBuilderFactory=DocumentBuilderFactory.newInstance();//DocumentBuilderdocumentBuilder=documentBuilderFactory.newDocumentBuilder();//Documentdocument=documentBuilder.newDocument();//returndocument;//}//catch(Exceptione){//log.error("error in createNewDocument",e);//throwe;//}//}//privatevoiddoProcessingInstructions(ElementprocessingInstructionsElement,ElementrootElement)throwsException{//try{//Stringxslt=xPathHelper.getString("xslt",processingInstructionsElement);//Stringcss=xPathHelper.getString("css",processingInstructionsElement);//if(!xslt.equals("")){//if(0==1){////notnow-tobedoneprocessingXMLusingXSLTinthisprogram//}//else{//ProcessingInstructionxmlstylesheet=outDocument.createProcessingInstruction("xml-stylesheet","type=\"text/xsl\" href=\""+xslt+"\"");//outDocument.insertBefore(xmlstylesheet,rootElement);//}//}//if(!css.equals("")){//ProcessingInstructionxmlstylesheet=outDocument.createProcessingInstruction("xml-stylesheet","type=\"text/css\" href=\""+css+"\"");//outDocument.insertBefore(xmlstylesheet,rootElement);//}//}//catch(Exceptione){//log.error("error in doProcessingInstructions",e);//throwe;//}//}//processTABLEelementsshouldbebettercommentedprivatevoidprocessTableElement(ElementtableElement)throwsException{//Whatshouldthiselementbenamed.StringtableElementName=tableElement.getAttribute("xmlName");//getSQLSELECTstatementtobeusedforquerycolumnvaluesStringtableSql=tableElement.getAttribute("sql");Stringprepared=tableElement.getAttribute("isPrepared");booleanisPrepared=false;ArrayListparamVals=newArrayList();if(prepared!=null&&prepared.trim().length()>0){isPrepared=Boolean.parseBoolean(prepared);}if(isPrepared){//Processallthe<prepared...>elementstocreatereplacementsNodeListnl=tableElement.getChildNodes();for(inti=0;i<nl.getLength();i++){if(nl.item(i).getNodeName()=="replacement"){Elementelem=(Element)nl.item(i);Stringorder=elem.getAttribute("order");Stringtype=elem.getAttribute("paramType");//Notreallyavalueyet,buttheglobalvariabletouse.Stringvalue=elem.getAttribute("parameter");Stringtemplate=elem.getAttribute("conversionTemplate");ReplacementValuerv=newReplacementValue();rv.setOrder(Integer.parseInt(order));rv.setType(type);rv.setValue(value);rv.setConversionTemplate(template);paramVals.add(rv);}}}//replaceglobalvariablesnamesbytheirvaluesStatementstatement=null;PreparedStatementpreparedStatement=null;ResultSetresultSet=null;try{if(isPrepared){preparedStatement=getPreparedStatement(connection,tableSql);resultSet=getResultSet(preparedStatement,paramVals);}else{tableSql=replaceGlobalVariable(tableSql);statement=getStatement(connection);resultSet=getResultSet(statement,tableSql);}while(resultSet.next()){//eachrecordisencapsulatedbytablexmlNamewriter.writeStartElement(tableElementName);//ElementnewElement=outDocument.createElement(tableElementName);NodeListnl=tableElement.getChildNodes();//walkthrougheachcolumnoftableelementfor(inti=0;i<nl.getLength();i++){//XSDensurescolumnsfirst,tablesecondif(nl.item(i).getNodeName()=="column"){processColumnElement((Element)nl.item(i),resultSet);}if(nl.item(i).getNodeName()=="replacement"){}if(nl.item(i).getNodeName()=="table"){processTableElement((Element)nl.item(i));}}writer.writeEndElement();//parentElement.appendChild(newElement);}}catch(Exceptione){log.error("tableSql=\""+tableSql+"\", multiStatementDriver=\""+multiStatementDriver+"\"");log.error("error in processTableElement",e);throwe;}finally{//DoSomecleanupif(resultSet!=null){try{resultSet.close();}catch(Exceptionignored){}}if(statement!=null&&!multiStatementDriver){try{statement.close();}catch(Exceptionignored){}}if(preparedStatement!=null){try{preparedStatement.close();}catch(Exceptionignored){}}}}//processCOLUMNelementsshouldbebettercommentedprivatevoidprocessColumnElement(ElementcolumnElement,ResultSetresultSet)throwsException{StringcolumnElementName=columnElement.getAttribute("xmlName");StringcolumnElementValue=columnElement.getAttribute("sqlName");StringcolumnGlobalVariableName=columnElement.getAttribute("globalVariableName");StringcharsetName=columnElement.getAttribute("charsetName");if(charsetName==null|charsetName==""){charsetName=globalCharsetName;}try{intcolumnIndex=resultSet.findColumn(columnElementValue);//indexofthisattributeintheResultSetStringcolumnValue=getColumnValueAsString(resultSet,columnIndex,charsetName);//isvalueofthiscolumnusedinsidefollowingSQLSELECTstatements?asglobalvariable...if(columnGlobalVariableName!=null){globalVariables.put(columnGlobalVariableName,columnValue);}//ElementnewElement=outDocument.createElement(columnElementName);//TextnewText=outDocument.createTextNode(columnValue);//newElement.appendChild(newText);//parentElement.appendChild(newElement);writer.writeStartElement(columnElementName);writer.writeCharacters(columnValue);writer.writeEndElement();}catch(Exceptione){log.error("xmlName=\""+columnElementName+"\", sqlName=\""+columnElementValue+"\", globalVariableName=\""+columnGlobalVariableName+"\", charsetName=\""+charsetName+"\"");log.error("error in processColumnElement",e);throwe;}}privatevoidsetReplacementValue(PreparedStatementps,intorder,Stringtype,StringconversionTemplate,StringrValue)throwsException{Stringvalue=(String)globalVariables.get(rValue);if(type.toLowerCase().trim().equals("string")){ps.setString(order,value);}elseif(type.toLowerCase().trim().equals("int")){ps.setInt(order,Integer.parseInt(value));}elseif(type.toLowerCase().trim().equals("long")){ps.setLong(order,Long.parseLong(value));}elseif(type.toLowerCase().trim().equals("double")){ps.setDouble(order,Double.parseDouble(value));}elseif(type.toLowerCase().trim().equals("float")){ps.setFloat(order,Float.parseFloat(value));}elseif(type.toLowerCase().trim().equals("date")){SimpleDateFormatsdf=newSimpleDateFormat(conversionTemplate);Dated=sdf.parse(value);ps.setDate(order,newjava.sql.Date(d.getTime()));sdf=null;}}//RegExpchangeglobalvariablesinSQLSELECTstatementusingregularexpressionprivateStringreplaceGlobalVariable(StringtableSql){Setset=globalVariables.keySet();Iteratoriterator=set.iterator();while(iterator.hasNext()){//walkthrougheachglobalvariablespairStringkey=(String)iterator.next();Stringvalue=(String)globalVariables.get(key);//herecanbeanerrorinRegEx-shouldbetestedbyuserstableSql=tableSql.replaceAll("\\"+key+"{1,}",value);//replacekey//byvalue}//end_whilereturntableSql;}//SQLgenericfunctionsprivateConnectiongetConnection(StringjdbcDriver,StringjdbcUrl,StringjdbcUserName,StringjdbcPassword)throwsException{try{Class.forName(jdbcDriver);Connectionconnection=DriverManager.getConnection(jdbcUrl,jdbcUserName,jdbcPassword);returnconnection;}catch(Exceptione){log.error("jdbcDriver=\""+jdbcDriver+"\", jdbcUrl=\""+jdbcUrl+"\", jdbcUserName and jdbcPassword are not logged");log.error("error in getConnection",e);throwe;}}privateStatementgetStatement(Connectionconnection)throwsException{try{//if-elsefordrivers,whichcannothavemultipleResultSet-speroneStatementif(!multiStatementDriver){returnconnection.createStatement();}else{if(globalStatement==null){globalStatement=connection.createStatement();}returnglobalStatement;}}catch(Exceptione){e.printStackTrace();log.error("connection=\""+connection+"\"");log.error("error in getStatement",e);throwe;}}privatePreparedStatementgetPreparedStatement(Connectionconnection,StringsqlSelect)throwsException{try{returnconnection.prepareStatement(sqlSelect);}catch(Exceptione){e.printStackTrace();log.error("connection=\""+connection+"\", sqlSelect=\""+sqlSelect+"\"");log.error("error in getPreparedStatement",e);throwe;}}/****Thestandardforusingregularstatements**@paramconnectionthesqlconnectiontouse*@paramsqlSelectthesqltoexecute-alreadyreplacedfromglobalvals*@returntheresultsetfromexecutingthestatement*@throwsException*/privateResultSetgetResultSet(Statementstatement,StringsqlSelect)throwsException{ResultSetretVal=null;try{retVal=statement.executeQuery(sqlSelect);}catch(Exceptione){log.error("statement=\""+statement+"\", sqlSelect=\""+sqlSelect+"\", multiStatementDriver=\""+multiStatementDriver+"\"");log.error("error in getResultSet",e);throwe;}returnretVal;}/****Thisimplementationisspecificallyforusingpreparedstatements.**@paramconnectionThesqlconnectiontouse*@paramsqlSelectthesqltoexecute*@paramparamValsthearraylistofparameters*@returntheresultsetfromexecutingthequery*@throwsException*/privateResultSetgetResultSet(PreparedStatementpreparedStatement,ArrayListparamVals)throwsException{ResultSetretVal=null;try{if(paramVals!=null&¶mVals.size()>0){for(inti=0;i<paramVals.size();i++){ReplacementValuerv=(ReplacementValue)paramVals.get(i);this.setReplacementValue(preparedStatement,rv.getOrder(),rv.getType(),rv.getConversionTemplate(),(String)rv.getValue());}}retVal=preparedStatement.executeQuery();}catch(Exceptione){log.error("connection=\""+connection+"\", multiStatementDriver=\""+multiStatementDriver+"\"");log.error("error in getResultSet",e);throwe;}returnretVal;}//TODOallowdifferenttypesmainlybooleanforchar(1)thatis"Y","y","N","n","0","1","T","t","F"or"f"forinstanceprivateStringgetColumnValueAsString(ResultSetresultSet,intcolumnIndex,StringcharsetName)throwsException{ResultSetMetaDataresultSetMetaData=resultSet.getMetaData();try{switch(resultSetMetaData.getColumnType(columnIndex)){casejava.sql.Types.VARCHAR:casejava.sql.Types.CHAR:casejava.sql.Types.LONGVARCHAR://notused-seemsliketheJDBCdrivershouldreturnthestringinthecorrectcharacterset//byte[]byteArray=resultSet.getBytes(columnIndex);//if(byteArray==null||resultSet.wasNull()){//return"null";//}//else{//StringstringFromChar=newString(byteArray,charsetName);//returnstringFromChar;//}//end_if-elseStringstring=resultSet.getString(columnIndex);if(resultSet.wasNull()){return"";}else{returnstring;}//end_if-elsecasejava.sql.Types.DOUBLE:casejava.sql.Types.INTEGER:casejava.sql.Types.BIGINT:casejava.sql.Types.TINYINT:casejava.sql.Types.SMALLINT:casejava.sql.Types.REAL:casejava.sql.Types.FLOAT:casejava.sql.Types.DECIMAL:casejava.sql.Types.NUMERIC:casejava.sql.Types.BIT:StringstringFromNumeric=resultSet.getString(columnIndex);if(resultSet.wasNull()){return"";}else{returnstringFromNumeric;}//end_if-elsecasejava.sql.Types.BINARY:casejava.sql.Types.VARBINARY:casejava.sql.Types.LONGVARBINARY:StringstringFromBinary=resultSet.getString(columnIndex);if(resultSet.wasNull()){return"";}else{returnstringFromBinary;}//end_if-elsecasejava.sql.Types.DATE:java.sql.Datedate=resultSet.getDate(columnIndex);if(resultSet.wasNull()){return"";}else{returndate.toString();}//end_if-elsecasejava.sql.Types.TIME:java.sql.Timetime=resultSet.getTime(columnIndex);if(resultSet.wasNull()){return"";}else{returntime.toString();}//end_if-elsecasejava.sql.Types.TIMESTAMP:java.sql.Timestamptimestamp=resultSet.getTimestamp(columnIndex);if(resultSet.wasNull()){return"";}else{returntimestamp.toString();}//end_if-elsedefault:return"unsupported data type (CLOB and BLOB should be, ARRAY, REF, STRUCT, JAVA OBJECT hard to be)";}//end_switch}catch(Exceptione){log.error("resultSet=\""+resultSet+"\", column index=\""+columnIndex+"\", column type=\""+resultSetMetaData.getColumnType(columnIndex)+"\", charsetName=\""+charsetName+"\"");log.error("error in getColumnValueAsString",e);throwe;}}publicStringgetValuesOfGlobalVariables(){returnvaluesOfGlobalVariables;}publicvoidsetValuesOfGlobalVariables(StringvaluesOfGlobalVariables){this.valuesOfGlobalVariables=valuesOfGlobalVariables;}publicStringgetPathToOutputXmlFile(){returnpathToOutputXmlFile;}publicvoidsetPathToOutputXmlFile(StringpathToOutputXmlFile){this.pathToOutputXmlFile=pathToOutputXmlFile;if(log.isDebugEnabled()){log.debug("Path to output xml is "+pathToOutputXmlFile);}}publiclonggetTotalTime(){returntotalTime;}publicvoidsetTotalTime(longtotaltime){this.totalTime=totaltime;}publiclonggetXmlTime(){returnxmlTime;}publicvoidsetXmlTime(longxmltime){this.xmlTime=xmltime;}privatestaticbooleanisJaxpIncluded(StringversionString){booleanretVal=true;if(versionString!=null&&versionString.trim().length()>=3){versionString=versionString.substring(2,3);intversion=Integer.parseInt(versionString);if(version>=5){retVal=true;}}returnretVal;}classReplacementValue{privateintorder;privateStringtype;privateObjectvalue;privateStringconversionTemplate;publicvoidsetOrder(intorder){this.order=order;}publicintgetOrder(){returnthis.order;}publicvoidsetType(Stringtype){this.type=type;}publicStringgetType(){returnthis.type;}publicvoidsetValue(Objectvalue){this.value=value;}publicObjectgetValue(){returnthis.value;}publicvoidsetConversionTemplate(Stringtemplate){this.conversionTemplate=template;}publicStringgetConversionTemplate(){returnthis.conversionTemplate;}}}
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
FWIW, after making the changes mentioned earlier so it would work better with MySQL, I've also modified it so it uses XMLStreamWriter, allowing it to process larger files. Here's the updated Dbsql2xml.java file containing the changes for both MySQL and XMLStreamWriter: