Problem facing in SAX Parsing

Problem facing in SAX Parsing

I have facing the issue in SAX Parsing like i have got the xml and the xml structure is like below.

<?xml version="1.0" encoding="UTF-8" ?>
- <Customers>
- <Customer>
<CustName>M.T.C ALUPACK <CustName>
<CustId>06684209932</CustId>
<CountryCode>BH</CountryCode>
<BranchCode>06684</BranchCode>
<AccountNbrs />
</Customer>
- <Customer>
<CustName>AL HASSANAIN CO.WLL</CustName>
<CustId>06684210088</CustId>
<BranchCode>06684</BranchCode>
- <AccountNbrs>
<AccountNbr>0668421008800119BHD</AccountNbr>
<AccountNbr>0668421008800119USD</AccountNbr>
<AccountNbr>0668421008800216BHD</AccountNbr>
<AccountNbr>0668421008800119QAR</AccountNbr>
</AccountNbrs>
</Customer>
<Customer>
<CustName>M.T.C. ALUPACK <CustName>
<CustId>06684209916</CustId>
<CountryCode>BH</CountryCode>
<BranchCode>06684</BranchCode>
- <AccountNbrs>
<AccountNbr>0668420991600115BHD</AccountNbr>
<AccountNbr>0668420991600115EUR</AccountNbr>
<AccountNbr>0668420991600115USD</AccountNbr>
</AccountNbrs>
</Customer>
- <Customer>
<CustName>AL ZAIN AUTO SUPPLIES ESTABLISHMENT</CustName>
<CustId>06684209577</CustId>
<BranchCode>06684</BranchCode>
- <AccountNbrs>
<AccountNbr>0668420957700159BHD</AccountNbr>
<AccountNbr>0668420957700159EUR</AccountNbr>
<AccountNbr>0668420957700159USD</AccountNbr>
</AccountNbrs>
</Customer>
<Customers>

you can find the above xml there is no CountryCode in the second record and 4th records.
if that CountryCode is not present then i need to skip the total Customer tag.
so we were using the sax parcing in our application. can you please let me know... how to handle this code in SAX Parcing.

Please find the below code which i have used..from the parcing point of view it is working very find..

package com.bnpparibas.tradefinance.batch.atlas2;

import java.io.File;
import java.io.FileReader;
import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Set;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

import com.bnpparibas.tradefinance.batch.util.IBatchConstants;
import com.bnpparibas.tradefinance.common.bean.db.Branch;
import com.bnpparibas.tradefinance.common.bean.db.Country;
import com.bnpparibas.tradefinance.common.bean.db.Customer;
import com.bnpparibas.tradefinance.common.bean.db.CustomerAccount;
import com.bnpparibas.tradefinance.common.bean.db.MO;
import com.bnpparibas.tradefinance.common.exception.DatabaseException;
import com.bnpparibas.tradefinance.ejb.facade.EjbFacade;
import com.bnpparibas.tradefinance.ejb.facade.EjbFacadeHome;
import com.ideo.sweetdev.core.log.ILog;
import com.ideo.sweetdev.core.log.LogHelper;
import com.ideo.sweetdev.core.service.remoting.IRemotingConstants;


/**
* Atlas2CustomerBatch ? This Class used to run the Batch to update the
* Customer Data in the Database Table Customer.
*
* @date 21/01/2009
* @revision 001
*
*/
public class Atlas2CustomerBatch extends DefaultHandler {


private Set accounts; // set of accounts for a single customer

private Customer customer; // A single customer

private String stringValue = "";

private CustomerAccount customerAct; //

String charValue = "";

private Branch branch = null;

private Country country = null;

private static EjbFacade ejbFacade = null;

private Map event = null;

private Set customers;

private static String CLASS_NAME = Atlas2CustomerBatch.class.getName();

private static ILog logger = LogHelper.getLog(CLASS_NAME);

/**
* main
*
* @param args
* @throws Exception
*/

public static void main(String args[]) throws Exception {
ResourceBundle customerResource = ResourceBundle
.getBundle("props.interfacecommon");
String cftFolderName = customerResource
.getString("customer.batch.cftfolder");
String processedFolderName = customerResource
.getString("customer.batch.processedfolder");
File cftcustomerFolder = new File(cftFolderName);
// Create a properties collection
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY,
IBatchConstants .INITIAL_CONTEXT_FACTORY);
props.put(Context.PROVIDER_URL, customerResource
.getString("rmi.remoteserver.uri"));
logger.debug("[Atlas2CustomerBatch][main]"+customerResource
.getString("rmi.remoteserver.uri"));
// Cretae a new Context Object
Context ctx = new InitialContext(props);
// look for the EJB using the Context
Object obj = (Object) ctx
.lookup(customerResource
.getString("rmi.ejb.facade.lookup"));
EjbFacadeHome dataHome = (EjbFacadeHome) PortableRemoteObject.narrow(
obj, EjbFacadeHome.class);
// Create a EJB Facade
ejbFacade = dataHome.create();

if (cftcustomerFolder.exists() && cftcustomerFolder.isDirectory()) {
File[] cftFiles = cftcustomerFolder.listFiles();
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
Atlas2CustomerBatch handler = new Atlas2CustomerBatch();
xmlReader.setContentHandler(handler);
xmlReader.setErrorHandler(handler);

for (int i = 0; i < cftFiles.length; i++) {
FileReader customerXmlFile = new FileReader(cftFiles[i]);
xmlReader.parse(new InputSource(customerXmlFile));
cftFiles[i].renameTo(new File(processedFolderName + "/"
+ cftFiles[i].getName()));
}
}

}

public Atlas2CustomerBatch() {
super();
}

/**
* This method executes on the start of the document. on start of the
* document reset the table.
*
* @date 23/12/2008
*/
public void startDocument() {

customers = new HashSet();


}

/**
* endDocument-XMLParser Event handler This method executes on the end of
* the document. on end of the document set the customer table.
*
*
*/
public void endDocument() {

// Truncate the Customer Table
try {
event = new HashMap();

event
.put(IRemotingConstants.INTERFACE_CLASS_NAME,
IBatchConstants.DATABASE_BUSINESS_CONTROLLER);
event.put(IRemotingConstants.METHOD_NAME, IBatchConstants.DATABASE_RESET_CUSTOMER);
ejbFacade.execute(event);

} catch (DatabaseException e) {
logger.error(e.getMessage() + e.getStackTrace());

} catch (RemoteException e) {
e.printStackTrace();
logger.error(e.getMessage() + e.getStackTrace());

} catch (Exception e) {
logger.error(e.getMessage(), e);

}

// Add the cutomers to the table
try {
if (customers == null) {
logger.debug("It is finding null here");
} else {
Customer customer1 = null;
Iterator itr = customers.iterator();

Class[] methodParameterTypesCustomer = { Customer.class };

while (itr.hasNext()) {
customer1 = (Customer) itr.next();

if (customer1 != null) {
if (customer.getCustomerId().length() > 0) {
Object[] cusotomerArguments = { (Object) customer1 };
event = new HashMap();
event
.put(
IRemotingConstants.INTERFACE_CLASS_NAME,
IBatchConstants.DATABASE_BUSINESS_CONTROLLER);
event.put(IRemotingConstants.METHOD_NAME,
IBatchConstants.DATABASE_SET_CUSTOMER);
event.put(
IRemotingConstants.METHOD_PARAMETER_TYPES,
methodParameterTypesCustomer);
event.put(IRemotingConstants.METHOD_ARGUMENTS,
cusotomerArguments);
ejbFacade.execute(event);
}
}
}
}
} catch (RemoteException e) {
logger.error(e.getMessage(), e);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}

}

/**
* startElement-XMLParser Event handler This method executes on the start of
* the elements. on start of the each element update the element in the
* customer bean
*
* @param uri
* @param name
* @param qName
* @param atts
*
*/

public void startElement(String uri, String name, String qName,
Attributes atts) {
if ("".equals(uri)) {
if (qName.equals(IBatchConstants.ATLAS2_CUSTOMER_QNAME_CUSTOMER)) {
// Create a new Customer bean here
customer = new Customer();
accounts = new HashSet();
}
// intialise the stringValue
stringValue = "";

}
}

/**
* endElement-XMLParser Event handler This method executes on the end of the
* elements. on end of the each element update the element in the customer
* bean
*
* @param uri
* @param name
* @param qName
*
*/

public void endElement(String uri, String name, String qName) {
String branchCode = "";
String countryCode = "";

MO mo = null;
if ("".equals(uri)) {
if (qName.equals(IBatchConstants.ATLAS2_CUSTOMER_QNAME_CUSTOMERNAME)) {
System.err.println("Customer Name:"+stringValue);
customer.setCustomerName(stringValue);
}
if (qName.equals(IBatchConstants.ATLAS2_CUSTOMER_QNAME_ID)) {
customer.setCustomerId(stringValue);
}

if (qName.equals(IBatchConstants.ATLAS2_CUSTOMER_QNAME_ACC_NMBR)) {
customerAct = new CustomerAccount();
customerAct.setAccountNumber(stringValue);
accounts.add(customerAct);
}

if (qName.equals(IBatchConstants.ATLAS2_CUSTOMER_QNAME_ACC_NUMBERS)) {
// Add the Accounts set to customer
if (accounts != null) {
customer.setAccounts(accounts);
}
}

if (qName.equals(IBatchConstants.ATLAS2_CUSTOMER_QNAME_COUNTRY_CODE)) {
countryCode = stringValue;
System.err.println("Country Code:"+stringValue);
try {
Class[] _methodParameterTypes = { String.class };
Object[] arguments = { (Object) countryCode };
event = new HashMap();
event
.put(IRemotingConstants.INTERFACE_CLASS_NAME,
IBatchConstants.DATABASE_BUSINESS_CONTROLLER);
event.put(IRemotingConstants.METHOD_NAME,
IBatchConstants.DATABASE_COUNTRY_BY_COUNTRY_CODE);
event.put(IRemotingConstants.METHOD_PARAMETER_TYPES,
_methodParameterTypes);
event.put(IRemotingConstants.METHOD_ARGUMENTS, arguments);
country = (Country) ejbFacade.execute(event);
}
catch (NumberFormatException e) {
logger.error(e.getMessage(), e);

} catch (DatabaseException e) {
logger.error(e.getMessage(), e);

} catch (RemoteException e) {
logger.error(e.getMessage(), e);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}


if (qName.equals(IBatchConstants.ATLAS2_CUSTOMER_QNAME_BRANCH_CODE)) {
branchCode = stringValue;
if (branchCode.length() > 0) {

try {
Class[] _methodParameterTypes = { String.class };
Object[] arguments = { (Object) branchCode };
event = new HashMap();
event
.put(IRemotingConstants.INTERFACE_CLASS_NAME,
IBatchConstants.DATABASE_BUSINESS_CONTROLLER);
event.put(IRemotingConstants.METHOD_NAME,
IBatchConstants.DATABASE_BRANCH_BY_BRANCH_CODE);
event.put(IRemotingConstants.METHOD_PARAMETER_TYPES,
_methodParameterTypes);
event.put(IRemotingConstants.METHOD_ARGUMENTS,
arguments);
branch = (Branch) ejbFacade.execute(event);

} catch (NumberFormatException e) {
logger.error(e.getMessage(), e);

} catch (DatabaseException e) {
logger.error(e.getMessage(), e);

} catch (RemoteException e) {
logger.error(e.getMessage(), e);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}

}
}

if (qName.equals(IBatchConstants.ATLAS2_CUSTOMER_QNAME_CUSTOMER)) {

// Got a Customer so update it in the customers set
if (country !=null && branch !=null){
try {

Class[] _methodParameterTypes = { Country.class,
Branch.class };

Object[] arguments = { (Object) country, (Object) branch };
event = new HashMap();
event
.put(IRemotingConstants.INTERFACE_CLASS_NAME,
IBatchConstants.DATABASE_BUSINESS_CONTROLLER);
event.put(IRemotingConstants.METHOD_NAME,
IBatchConstants.DATABASE_MO_BY_COUNTRY_AND_BRANCH);
event.put(IRemotingConstants.METHOD_PARAMETER_TYPES,
_methodParameterTypes);
event.put(IRemotingConstants.METHOD_ARGUMENTS, arguments);
mo = (MO) ejbFacade.execute(event);


} catch (DatabaseException e) {
logger.error(e.getMessage(), e);

} catch (RemoteException e) {
logger.error(e.getMessage(), e);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
if (mo !=null){

customer.setMiddleOffice(mo.getId());
customers.add(customer);
}else{
logger.error("Mo not found for Country or branch in Database.");
}

}else{
logger.error("Country or branch not available in Database.");
}

}

if (qName.equals(IBatchConstants.ATLAS2_CUSTOMER_QNAME_CUSTOMERS)) {
// end of list of customer
}

}

}

/**
*
* This method reads the value of XML elements.called by XML sex parser
*
* @param chArray -
* array of characters
* @param start
* @param length
*
*/
public void characters(char chArray[], int start, int length) {

for (int i = start; i < start + length; i++) {
if (!(chArray[i] == '\\' || chArray[i] == '"' || chArray[i] == '\n'
|| chArray[i] == '\r' || chArray[i] == '\t')) {
charValue = String.valueOf(chArray[i]);
stringValue = stringValue + charValue;
}

}
}
}


Thanks In Advance....

cheers,
Sunil
View Answers









Related Tutorials/Questions & Answers:
Problem facing in SAX Parsing - XML
Problem facing in SAX Parsing  I have facing the issue in SAX Parsing... tag. so we were using the sax parcing in our application. can you please let me know... how to handle this code in SAX Parcing.   Hi Friend, First
Problem facing in SAX Parsing - XML
Problem facing in SAX Parsing  I have facing the issue in SAX Parsing... then i need to skip the total Customer tag. so we were using the sax parcing in our application. can you please let me know... how to handle this code in SAX
Advertisements
parsing xml using sax
parsing xml using sax  how to get values if the root elements are same and their attributes are different
Truncating issue while parsing XML with SAX Parser.
Truncating issue while parsing XML with SAX Parser.  I am Parsing one xml file and after parsing I have to enter the data into the database using hibernate. The problem is while parsing some elements, its not getting the complete
XML Parsing Using Sax Parser in J2ME for serverside
XML Parsing Using Sax Parser in J2ME for serverside  Hai team, i have doubt in Parsing using sax parser in serverside plz help me for xml parsing in j2me using sax parser on server side thanks in advance... regards Selva
XML Parsing Using Sax Parser in J2ME
XML Parsing Using Sax Parser in J2ME  Hai team, I hope you, You should help me, I have trouble in Xml parsing... I have decoded value, what... to do xml parsing help me for that... Regards Alagu
facing problem plz help me out - Framework
Facing problem plz help me out  hi i am new to servlet i deployed... the web.xml file too parallel to the classes folder now i am facing this problem.plz tell me what to do... error:The requested resource (Servlet servlet
parsing word xml file using SAX parser - XML
parsing word xml file using SAX parser  i am parsing word 2003's XML file using SAX.here my question is,i want to write some tag elements which are between in other tag to a file. For ex
Parsing repeatitive xml elements using SAX Parser - XML
Parsing repeatitive xml elements using SAX Parser  Hi, I'm using SAX Parser to read an XML file. My XML file contains repeatitive tags. I'm... SAX parser. Thanks. Thanks.  Hi Shailendra, Use the following
Facing Problem to insert Multiple Array values in database - JSP-Servlet
Facing Problem to insert Multiple Array values in database  Hai... facing the problem while inserting the data in database. iam using the MsAccess... Manoj   Hi friend, You Have Problem in Data Table and check
Facing Problem with submit and cancel button in same page - Struts
Facing Problem with submit and cancel button in same page  Hi, can u please help me out.I have placed submit and cancel button in the jsp page but i am unable to know how to write the form and action classes   Hi
facing problem while retrive value from Post textarea
facing problem while retrive value from Post textarea  Hi this is subha. I face a small problem while retriving value of the textbox in the java script.I use struts framework and this is my code for post textarea. <tr>
Java XML Parsing Using SAX
Java XML Parsing Using SAX To Parse XML document using SAX parser method you...;/Students> 1. At first Create the SAX Parser as // getting SAXParserFactory... = saxParserFactory.newSAXParser(); // Parsing XML Document by calling parse
Version of sax>sax dependency
List of Version of sax>sax dependency
facing problem plz help me out - Framework
Facing - Ajax
Facing   Hello All, i m using ajax in my application i m fetching data from db using ajax method and returning response in xml format. But when... the problem. once check u r xml response format. xml response should be like
XML parsing to Mysql database
XML parsing to Mysql database  Can someone please post the code for parsing an XML file into Mysql database using SAX
DOM to SAX and SAX to DOM - XML
Java DOM to SAX and SAX to DOM  Simple API for XML and Document Object Model
DOM to SAX and SAX to DOM - XML
DOM SAX Parser Java  What is the Difference between SAX and DOM parsers
Artifacts of sax
List of Artifacts of sax maven depenency
parsing XML file to get java object - XML
parsing XML file to get java object  Hello, I'm facing a problem in parsing XML file to get the java object. I've tried to retrieve data from XML file using SAX parser. my XML file structure is the following
Maven Repository/Dependency: sax | sax
Maven Repository/Dependency of Group ID sax and Artifact ID sax. Latest version of sax:sax dependencies. # Version Release Date You can read more at: Maven Tutorials What
sax parser for xml
sax parser for xml  sax parser code that works with any XML i.e independent of any XML to extract data from XML
Maven Dependency sax >> 2.0.1
You should include the dependency code given in this page to add Maven Dependency of sax >> sax version2.0.1 in your project
The Simple API for XML (SAX) APIs
The Simple API for XML (SAX) APIs       The SAX Packages: The SAX parser is defined in the following... Description org.xml.sax Defines the SAX interfaces
SAX Parser exception
SAX Parser exception  I am trying to validate one xml, its giving me exception as : cvc-elt.5.2.2.1:The value '00' of element 'abcd' does not match the fixed {value constraint} '0'. Please help me asap
ModuleNotFoundError: No module named 'torchnet-sax'
ModuleNotFoundError: No module named 'torchnet-sax'  Hi, My Python... 'torchnet-sax' How to remove the ModuleNotFoundError: No module named 'torchnet-sax' error? Thanks   Hi, In your python
ModuleNotFoundError: No module named 'torchnet-sax'
ModuleNotFoundError: No module named 'torchnet-sax'  Hi, My Python... 'torchnet-sax' How to remove the ModuleNotFoundError: No module named 'torchnet-sax' error? Thanks   Hi, In your python
XML parsing using Java - XML
" RenewalRate1="0.03100". I'm facing problem switching between tables. Like...XML parsing using Java  I'm trying to parse a big XML file in JAVA. The goal is like i will take console input from user until "Coverage
SAX Parser
SAX Parser       The Simple API for XML (SAX) is a serial access parser API for XML. It is used... executes, the SAX parser recognizes and responds to each XML structure taking
java input problem - Java Beginners
java input problem  I am facing a Java input problem
ModuleNotFoundError: No module named 'parsing'
ModuleNotFoundError: No module named 'parsing'  Hi, My Python... 'parsing' How to remove the ModuleNotFoundError: No module named 'parsing... to install padas library. You can install parsing python with following command
parsing xml file in jsp
parsing xml file in jsp  example that pars XML file in JSP
Major challenges that organizations facing which containerization solved
Major challenges that organizations facing which containerization solved ... to solve application deployment problem in my enterprise. What are the Major challenges that organizations facing which containerization solved? Can any one
parsing xml with jquery
parsing xml with jquery  Please explain how to parse a xml file into jquery. Thanks
SAX Parser for huge XML file
SAX Parser for huge XML file  Hi.... if the XML file is small and repetitive then this will have meaning.. import javax.xml.parsers.... using sax parser... i wanna use direct file path... not by defining each and every
Parsing string in objective c
Parsing string in objective c  Hi, How can i parse a string in Objective c?? Thanks.   Parsing string in objective c This example will also help you to separate the strings separated by one component
Parsing date in Java
Parsing date in Java  How can i parse the date in Java in a simple format..?   SimpleDateFormat parserSDF=new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy
Parsing into date object
Parsing into date object  Here is my code: String de = (String) session.getAttribute("licvalid"); DateFormat df = new SimpleDateFormat("yyyy/MM/dd.... But, it is showing error at the line where i performed parsing operation. Please help me
Parsing into date object
Parsing into date object  Here is my code: String de = (String) session.getAttribute("licvalid"); DateFormat df = new SimpleDateFormat("yyyy/MM/dd.... But, it is showing error at the line where i performed parsing operation. Please help me
jsp reload current page problem
jsp reload current page problem  Hi, i am facing problem while reloading the JSP page
jsp reload current page problem
jsp reload current page problem  Hi, i am facing problem while reloading the JSP page
problem in programming - JSP-Servlet
problem in programming  Hi! I am new with jsp. I am facing a problem in programming to calculate the time interval between login time and logout time of user
java parsing of data types
java parsing of data types  Why its not works? char ch; String s=* ch=Character.parseChar(s) program: char op; DataInputStream dis=new DataInputStream(System.in); System.out.print("Enter operator (+,-,*,/,%): "); op
xml document parsing
xml document parsing   Hi Guys, Xml document has been inserted into the database,how do i parse the xml document stored in database,so that xml document can be retrieved on to JSP file using jdbc/odbc connection. Please help me
Html Parsing Extracting Content
Html Parsing Extracting Content  Hello i need to parse html and search for a string and get its attributes.For example 'xxx' is my search string. i search html page and find xxx css attributes.Java,php,javascript is okey thank
xml parsing - XML
± how can i do this?   Hi friend, Parsing The XML File using DOM parser in JSP visit to : http://www.roseindia.net/jsp/parsing-xml.shtml
Problem with cookies
Problem with cookies  Hello All, i need jsp code for RememberMe module of login. i am facing problem with cookies. so please if any one could guide me please help and provide mme the exact code.   Please visit
Parsing a pharase - Java Beginners
Parsing a pharase  How do parse a sentence or pharse from a given passage?? Thank you in advance, plz help.  it can be done in many ways some of them are String.split methods StringTokenizer and StreamTokenizer
ModuleNotFoundError: No module named 'parsing-tools'
ModuleNotFoundError: No module named 'parsing-tools'  Hi, My... 'parsing-tools' How to remove the ModuleNotFoundError: No module named 'parsing-tools' error? Thanks   Hi, In your python

Ads