Problem in using SAX parser.
Hai All,
I have got a problem in using SAX parser.
My XML looks like this:
<authorizer>
<first-name>HP</first-name>
<last-name>Services</last-name>
<phone>800-22-1984</phone>
</authorizer>
<destination>
<first-name>John</first-name>
<last-name>Doe</last-name>
<company>John Doe Enterprises, Inc.</company>
<department>Manufacturing</department>
<phone>800-555-1234</phone>
<address>
<street-one>1654 Peachtree Str</street-one>
<street-two>Suite Y</street-two>
<city>Atlanta</city>
<province>GA</province>
<country>US</country>
<postal-code>30326</postal-code>
</address>
</destination>
my part of SAX parser code is:
public void startElement (String name, AttributeList attrs)
throws SAXException
accumulator.setLength(0);
public void characters (char buf [], int offset, int len)
throws SAXException
accumulator.append(buf, offset, len);
public void endElement (String name)
throws SAXException
if (name.equals("first-name") )
firstname=accumulator.toString().trim();
if (name.equals("last-name"))
lastname=accumulator.toString().trim();
My problem is that i have to store the values of first-name and last-name.
but i have that in both
<authorizer> </authorizer> Tag and
<destination> </destination>
I need to retrive authorizer's firstname,lastname and
destination's firstname and lastname.
what i mean is i need to store authorizerFirstName,authorizerLastName
destinationFirstname and destinationLastname.
Pls let me know how to do that.
Thanks in advance.
Pooja.
hi pooja,
I think you are using DataHandler for parsing. Its deprecated. try using contentHandler . You can get the value of the element at the beginning. say for example
<firstname>sdfs</firstname>
the startElement will be firstname
the next method that it invokes will be characters method which has the text associated with the element. I am sending a sample code for your problem. try using it .
boolean m_boolinAuth = false;
boolean m_boolinDest = false;
boolean m_bAuthFName = false;
boolean m_bAuthLName = false;
public void startElement(String namespaceURI, String elementName, String qName, Attributes atts)
//does the logic for startElement
if(qName.equals("Authorization"))
m_boolinAuth = true;
m_boolinDest = false;
else if(qName.equals("Destination"))
m_boolinDest = true;
m_boolinAuth = false;
if(qName.equals("firstname"))
m_bFirstName = true;
if(qName.equals("lastname"))
m_bLastName = true;
public void characters(char[] ch, int start, int length)
//does the logic for characters.
String str = new String(ch,start,length);
if(m_bFirstName)
if(m_boolinAuth)
m_strAuthFirstName =str;
else if(m_boolinDest)
m_strDestFirstName = str;
m_bFirstName = false;
if(m_bLastName)
//same as first name case;
}
Similar Messages
-
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; -
Code to read xml file and display that data using sax parser
Hai
My problem I have to read a xml file and display the contents of the file on console using sax parser.here you go
-
Hello
I need to convert xml files to csv format using SAX Parser. The following code & outputs are as below:
XML file:
<Library>
<Book>
<Title>Professional JINI</Title>
<Author>bs</Author>
<Publisher>Oreilly Publications</Publisher>
</Book>
<Book>
<Title>XML Programming</Title>
<Author>java</Author>
<Publisher>Mann Publications</Publisher>
</Book>
</Library>
public class BooksLibrary extends DefaultHandler
protected static final String XML_FILE_NAME = "C:\\library1.xml";
public static void main (String argv [])
// Use the default (non-validating) parser
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
FileOutputStream fos=new FileOutputStream("C:/test.txt");
// Set up output stream
out = new OutputStreamWriter (fos, "UTF8");
// Parse the input
SAXParser saxParser = factory.newSAXParser();
saxParser.parse( new File(XML_FILE_NAME), new BooksLibrary() );
} catch (Throwable t) {
t.printStackTrace ();
System.exit (0);
static private Writer out;
//===========================================================
// Methods in SAX DocumentHandler
//===========================================================
public void startDocument ()
throws SAXException
showData ("<?xml version='1.0' encoding='UTF-8'?>");
newLine();
public void endDocument ()
throws SAXException
try {
newLine();
out.flush ();
} catch (IOException e) {
throw new SAXException ("I/O error", e);
public void startElement (String name, Attributes attrs)
throws SAXException
showData ("<"+name);
if (attrs != null) {
for (int i = 0; i < attrs.getLength (); i++) {
showData (" ");
showData (attrs.getLocalName(i)+"=\""+attrs.getValue (i)+"\"");
showData (">");
public void endElement (String name)
throws SAXException
showData ("</"+name+">");
public void characters (char buf [], int offset, int len)
throws SAXException
String s = new String(buf, offset, len);
showData (s);
//===========================================================
// Helpers Methods
//===========================================================
// Wrap I/O exceptions in SAX exceptions, to
// suit handler signature requirements
private void showData (String s)
throws SAXException
try {
out.write (s);
out.flush ();
} catch (IOException e) {
throw new SAXException ("I/O error", e);
// Start a new line
private void newLine ()
throws SAXException
//String lineEnd = System.getProperty("line.separator");
try {
out.write (", ");
} catch (IOException e) {
throw new SAXException ("I/O error", e);
--------------------------------------------------------------------------------------------------output is as follows:
<?xml version='1.0' encoding='UTF-8'?>,
Professional JINI
bs
Oreilly Publications
XML Programming
java
Mann Publications
Can anyone please tell me how to remove that indentation space & get the output as :
<?xml version='1.0' encoding='UTF-8'?>, Professional JINI, bs, Oreilly Publications, XML Programming, java, Mann Publications
ThanksBy the way, there is a new feature in Java 5.0 (Tiger) called "Annotations."
Since your code extneds DefaultHandler, you could specify a line with
@Override
before the definition of each of your methods. If you had used these, the compiler would have given an error since your methods did not override the methods of DefaultHandler.
(If your code implemented ContentHandler, by contrast, using @Override is invalid because you need to implement all of the methods defined in the interface definition.)
The other comment is that the safest way to handle characters() data is to use a StringBuilder/Buffer (StringBuilder is only valid in 5.0, StringBuffer has been around since Release 1.0) that you define in the startElement method. Use the append method to gather data presented to you in the characters() method and use toString() to harvest the data in the endElement method.
Dave Patterson -
Please help me how to use SAX parser in J2ME.
Is there any function to find the value of a particular element from a XML file?
I am able to get Element name, Values, Attributes. But control is not in my hand, DefaultHanldler automatically invokes Character method, then only I am able to get values. But I don't know when this method gets invoked.
Is there any way or method so that I can get value of any element or attribute just by passing element name as parameter in SAX parser?
Is there any other parser through which I can perform this task in J2ME?
Thanks in advance.Hi..
have a look at this.
http://www-128.ibm.com/developerworks/library/wi-parsexml/
MeTitus -
Read any XML File Elements using SAX Parser in J2se
Hi All
I can able to parsed one structured XML file using SAX
Sample code :
// ===========================================================
// SAX DocumentHandler methods
// ===========================================================
public void startDocument() throws SAXException {
logger.info("Start of document");
public void endDocument() throws SAXException {
logger.info("End of document");
public void startElement(String namespaceURI, String localName, // local
// name
String qualName, // qualified name
Attributes attrs) throws SAXException {
elemName = new String(localName); // element name
if (elemName.equals(""))
elemName = new String(qualName); // namespaceAware = false
tagPosition = TAG_START;
// Set the string for accumulating the text in a tag to empty
elemChars = "";
// If the element name is "row", create a new row instance
// If the element is "indexxid", "ModelPrice", or "ModelSpread",
// the value will be read in the method "characters" and stored.
if (elemName.equals("row")) {
row = new IndexRow();
numRows++;
// logger.info("Number of numRow:"+numRows);
} // end method startElement
public void endElement(String namespaceURI, String simpleName, // simple
// name
String qualName // qualified name
) throws SAXException {
elemName = new String(simpleName);
if (elemName.equals(""))
elemName = new String(qualName); // namespaceAware = false
tagPosition = TAG_END;
String indexId = new String();
Double dblVal = new Double(0);
// If element name is "row", put the current row in the map for row
// instances
if (elemName.equals("row")) {
if (numRows <= 5) { logger.info("Row is: " + row.toString()); }
//ABX
//indexRows.put(row.getIndexxId(), row);
if (family.equals("ABX.HE")){
indexRows.put(row.getIndexREDId(), row);
else {
//CDX ITRXX
indexRows.put(row.getIndexxId(), row);
} else if (elemName.equals("IndexID")) {
row.setIndexxId(elemChars);
// Leave double value at default of zero if there are no chars
if (elemChars.trim().length() != 0) {
dblVal = new Double(elemChars);
row.setCompositeSpread(dblVal);
indexId = row.getIndexxId();
} else if (elemName.equals("REDCode")) {
row.setRedCode(elemChars);
else if (elemName.equals("Name")) {
row.setRowName(elemChars);
} else if (elemName.equals("Series")) {
row.setSeries(elemChars);
} else if (elemName.equals("Version")) {
row.setVersion(elemChars);
} else if (elemName.equals("Term")) {
row.setTerm(elemChars);
} else if (elemName.equals("Maturity")) {
row.setMaturity(elemChars);
} else if (elemName.equals("OnTheRun")) {
row.setOnTheRun(elemChars);
} else if (elemName.equals("Date")) {
row.setRowDate(elemChars);
} else if (elemName.equals("Depth")) {
row.setDepth(elemChars);
else if (elemName.equals("Heat")) {
// logger.info("Chars for element " + elemName + " are '" +
// elemChars + "'");
// Leave double value at default of zero if there are no chars
if (elemChars.trim().length() != 0) {
dblVal = new Double(elemChars);
row.setHeat(dblVal);
indexId = row.getIndexxId();
// ABX.HE
else if (elemName.equals("IndexREDId")){
row.setIndexREDId(elemChars);
else if (elemName.equals("Coupon")){
row.setCoupon(elemChars);
if (elemName.equals("Ontherun")) {
row.setOnTheRun(elemChars);
} // end method endElement
public void characters(char buf[], int offset, int len) throws SAXException {
// If at end of element, there will be no characters
if (tagPosition == TAG_END) {
return;
// The characteres method may be called more than once
// for an element if the internal buffer fills up.
// Append the characters until the end of the element.
String strVal = new String(buf, offset, len);
elemChars = elemChars + strVal;
} // end method characters
} // end class MarkItIndexLoader
but the problem is i want to read (parse) any XML file means any Elemets would be change any time using SAX .In the above example
else if (elemName.equals("Heat")) {
else if (elemName.equals("IndexREDId")){
} else if (elemName.equals("Maturity")) {
like above I am doing hard code Elements names and reading the values so i don't want hard coding the elements names I want to read any element name and value dynamically.
If i give any one below XML file i want to read the Elements and displaying to console without changing any code i want to read the XML document.
EX:
Student.XML: <root>..</StName>..</StAge>...</root>
Employee.XML: <root>..</EmpName>..</EmpAge>...</root>
CdCatalog.XML: <root>..</Cdtitle>...</CdNumber>...</root>
I need one java program can ready any type of XML file elements and send to the Database table.
Please any one done like this task please suggest some reference links or books or sample snippet which can help me to develop program in my requirement.
Thanks in advance
Regards
satishYou should ask in the Java forum.
Regards
Stefan -
Buiding xml file using SAX parser of JAXP
Please send me xml building using the sax parser.This is the urgent requirement ,iam not geeting how to solve this problem.so please anybody can help with one best example
You don't build an XML file with a parser. A parser reads an XML file and converts it to some internal representation. Try reading this tutorial:
http://java.sun.com/xml/jaxp/dist/1.1/docs/tutorial/ -
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 -
JAVA mapping using SAX parser adds extra tags
Hi,
We are using java mapping using a SAX parser.It works well in standalone application ie it parses correctly and gets our desired xml structure and the xml is well formed too but when we import it in XI as a jar file it does not throw any errors but adds extra start tags, as a result the output xml is not well formed.XI is adding extra start tags.
If any one else has faced a similar situation please help.
Regards,
Anirban.Hi Roberto,
Thank you for the response.
As I said, it doesnt throw any error. It is working perfectly in standalone application. But when we deploy it to XI Server, it is not forming the well formed XML. We too are puzzled by this situation.
Okay, i will explain my scenario here.
The following is my input XML to the java pgm..
<Header>
</Header>
<Body>
</Body>
<SubBody1>
</SubBody1>
<SubBody2>
</SubBody2>
<SubBody3>
</SubBody3>
<SubBody4>
</SubBody4>
<Trail>
</Trail>
The desired output is
<Header>
<Body>
<NameChanged1>
<NameChanged2>
<SubBody3>
<SubBody4>
</SubBody4>
</SubBody3>
</NameChanged2>
</NameChanged1>
<Trail>
</Trail>
Just look at the SubBody2 and SubBody1 node, its tag name has been changed in the output XML. Thats y i have decided to use java mapping instead of message mapping.
I have developed the code for everything, i.e for changing the tag name and for forming the nested xml and it is working fine as a standalone application. But while deploying it to XI, the output is not well formed. I dont know the reason for it. Even I have checked the cardinality of the output Data types, that I have created. Its perfectly okay with all.
Any Ideas???
Regards,
Anirban -
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.
-
SAX: How to create new XML file using SAX parser
Hi,
Please anybody help me to create a XML file using the Packages in the 5.0 pack of java. I have successfully created it reading the tag names and values from database using DOM but can i do this using SAX.
I am successful to read XML using SAX, now i want to create new XML file for some tags and its values using SAX.
How can i do this ?
Sachin KulkarniSAX is a parser, not a generator.Well,
you can use it to create an XML file too. And it will take care of proper encoding, thus being much superior to a normal textwriter:
See the following code snippet (out is a OutputStream):
PrintWriter pw = new PrintWriter(out);
StreamResult streamResult = new StreamResult(pw);
SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();
// SAX2.0 ContentHandler.
TransformerHandler hd = tf.newTransformerHandler();
Transformer serializer = hd.getTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");//
serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"pdfBookmarks.xsd");
serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"http://schema.inplus.de/pdf/1.0");
serializer.setOutputProperty(OutputKeys.METHOD,"xml");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
hd.setResult(streamResult);
hd.startDocument();
//Get a processing instruction
hd.processingInstruction("xml-stylesheet","type=\"text/xsl\" href=\"mystyle.xsl\"");
AttributesImpl atts = new AttributesImpl();
atts.addAttribute("", "", "someattribute", "CDATA", "test");
atts.addAttribute("", "", "moreattributes", "CDATA", "test2");
hd.startElement("", "", "MyTag", atts);
String curTitle = "Something inside a tag";
hd.characters(curTitle.toCharArray(), 0, curTitle.length());
hd.endElement("", "", "MyTag");
hd.endDocument();
You are responsible for proper nesting. SAX takes care of encoding.
Hth
;-) stw -
Problem Using Sax parser with Eclipse 3.0 and command line
Hi,
I am parsing a xml file with sax. When I am running my programm in the command line everthing is ok and I get the right results from parsing.
But if I am running the programm in Eclipse 3.0 (the same java code) I get an other result (the wrong results).
Does anybody know what this can be the reason for. Is Eclipse using an other xml parser and if where I can change the parser?
It would be very kind if somebody can give me a reason for this strange behaviour.
Thanks in advanceI have solved my problem.
In the command line I used jre 1.4 and in Eclipse I used jre 1.5.
I think jre 1.5 uses an other xml parser so I got an other result.
If i use in Eclipse jre1.4 I get the same result as in the command line. -
Problems with using SAXParser.parse with an InputStream
Hello:
I have successfully run the echo01 program from the XML tutorial. I made the following changes to parse the output from a servlet which generates an XML document.
URL recordedSensor = new URL("http://redbd01:8010/servlet/RecordedSensor?vin=1M000000000000001");
URLConnection rsConn = recordedSensor.openConnection();
// Parse the input
SAXParser saxParser = factory.newSAXParser();
saxParser.parse( rsConn.getInputStream(), handler);
I get the following errors when I try to run the code.
org.xml.sax.SAXParseException: java.lang.NullPointerException
at org.apache.crimson.parser.Parser2.parseInternal(Parser2.java:524)
at org.apache.crimson.parser.Parser2.parse(Parser2.java:305)
at org.apache.crimson.parser.XMLReaderImpl.parse(XMLReaderImpl.java:442)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:393)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:191)
at ServletInterface.main(ServletInterface.java:29)
I think I have the problem narrowed down to the handlers accessing the class variable out which is a Writer the emit() method uses to output the document. When I replace out.write in emit() with System.out.println() the code works.
I've tried accessing other class variables in the handler methods with similar results.
Anybody encountered similar problems? And what is the solution.
Thanks in advance,
GaryI have the same problem, if you find a solution let me know. I've double checked my objects to make sure their not null, I've checked my constructors in the extended default handler, not really sure where else to look, its such a simple program....
-
HO w to use SAX parser to create an XML file on the fly
Hi All,
Currently I am using the DOM parser to create an XML file from a text file. But as the DOM takes much memory and inefficient, I need to convert the DOM translator to SAX translator. Can I do that ?? If YES then how to go about that and if NO then what may be the workaround for that.
Please help me out
Thanx in advance
kaushikIncidentally, look at this thread:
http://forum.java.sun.com/thread.jsp?forum=34&thread=252415
It has an example of how to transform an XML file via XSLT. If you change this to use the zero-argument form of newTransformer, it will apply the "identity transformation" to your input, thus outputting your XML in valid form. Now you just need to figure out how to provide SAX input to this, and the JAXP download includes an example of that. -
hi,
i am assuming the problem is with sax parser but i cant be sure. I am parsing a xml file (about 1.4MB) with some data in it. the parser i have created reads the xml file correctly for the most part but when at some point the
"public void characters(char buf[], int offset, int len) throws SAXException"
function stops working correctly....i.e it doesnt fully read read the data between the "<start>" and "</start>" element. say it reads about 100 id's correctly---for 101 ID it does this. This is just an example. Since, the problem might be with how :
"public void characters(char buf[], int offset, int len) throws SAXException"
function is reading the data i was wondering if anybody else had encountered this problem or please let me know if i need to change something in the code: here's a part of the code :
Bascially i have created three classes to enter data into three mysql tables and as i parse the data i fill up the columns by matching the column header with the tagName.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.*;
import java.io.*;
import java.util.ArrayList;
import java.lang.Object;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import java.util.*;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
public class Echo03 extends DefaultHandler
StringBuffer textBuffer;
int issuedValue, prodValue;
OrdHeader header = new OrdHeader();
OrdDetail detail = new OrdDetail();
Member memInfo = new Member();
//new addition to store the dynamic value of the products
TestOrdheader prod = new TestOrdheader();
int counter;
String tag, newTag;
SetValue setVal = new SetValue();
String test;
public static void main(String argv[])
if (argv.length != 1) {
System.err.println("Usage: cmd filename");
System.exit(1);
// Use an instance of ourselves as the SAX event handler
DefaultHandler handler = new Echo03();
// Use the default (non-validating) parser
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
// Set up output stream
out = new OutputStreamWriter(System.out, "UTF8");
// Parse the input
SAXParser saxParser = factory.newSAXParser();
saxParser.parse( new File(argv[0]), handler);
} catch (Throwable t) {
t.printStackTrace();
System.exit(0);
static private Writer out;
private String indentString = " "; // Amount to indent
private int indentLevel = 0;
//===========================================================
// SAX DocumentHandler methods
//===========================================================
public void startDocument()
throws SAXException
nl();
nl();
emit("START DOCUMENT");
nl();
emit("<?xml version='1.0' encoding='UTF-8'?>");
header.assign();
public void endDocument()
throws SAXException
nl(); emit("END DOCUMENT");
try {
nl();
out.flush();
} catch (IOException e) {
throw new SAXException("I/O error", e);
public void startElement(String namespaceURI,
String lName, // local name
String qName, // qualified name
Attributes attrs)
throws SAXException
indentLevel++;
nl(); //emit("ELEMENT: ");
String eName = lName; // element name
if ("".equals(eName)) eName = qName; // namespaceAware = false
if (qName.equals("Billing")){
issuedValue = 1;
}else if (qName.equals("Shipping")){
issuedValue = 2;
}else if (qName.equals("ShippingTotal")){
issuedValue = 3;
//check to see if "Product" is the name of the element thats coming next
if (qName.equals("Product")){
if (issuedValue != 3){
prodValue = 1;
prod.addCounter();
}else{
prodValue = 0;
tag = eName;
if (attrs != null) {
for (int i = 0; i < attrs.getLength(); i++) {
String aName = attrs.getLocalName(i); // Attr name
if ("".equals(aName)) aName = attrs.getQName(i);
nl();
emit(" ATTR: ");
emit(aName);
emit("\t\"");
emit(attrs.getValue(i));
emit("\"");
if (attrs.getLength() > 0) nl();
public void endElement(String namespaceURI,
String sName, // simple name
String qName // qualified name
throws SAXException
nl();
String eName = sName; // element name
if ("".equals(eName)){
eName = qName; // not namespaceAware
if ("Order".equals(eName)){
//enter into database
databaseEnter();
textBuffer = null;
indentLevel--;
public void characters(char buf[], int offset, int len)
throws SAXException
nl();
try {
String s = new String(buf, offset, len);
if (!s.trim().equals("")){
settag(tag, s);
s = null;
}catch (NullPointerException E){
System.out.println("Null pointer Exception:"+E);
//===========================================================
// Utility Methods ...
//===========================================================
// Wrap I/O exceptions in SAX exceptions, to
// suit handler signature requirements
private void emit(String s)
throws SAXException
try {
out.write(s);
out.flush();
} catch (IOException e) {
throw new SAXException("I/O error", e);
// Start a new line
// and indent the next line appropriately
private void nl()
throws SAXException
String lineEnd = System.getProperty("line.separator");
try {
out.write(lineEnd);
for (int i=0; i < indentLevel; i++) out.write(indentString);
} catch (IOException e) {
throw new SAXException("I/O error", e);
===================================================================
///User defined methods
===================================================================
private String strsplit(String splitstr){
String delimiter = new String("=");
String[] value = splitstr.split(delimiter);
value[1] = value[1].replace(':', ' ');
return value[1];
public void settag(String tag, String s){
String pp_transid = null, pp_respmsg = null,pp_authid = null, pp_avs = null, pp_avszip = null;
if ((tag.equals("OrderDate")) || (tag.equals("OrderProcessingInfo"))){
if (tag.equals("OrderDate")){
StringTokenizer st = new StringTokenizer(s);
String orddate = st.nextToken();
String ordtime = st.nextToken();
header.put("ordDate", orddate);
header.put("ordTime", ordtime);
}else if (tag.equals("OrderProcessingInfo")){
StringTokenizer st1 = new StringTokenizer(s);
int tokenCount = 1;
while (tokenCount <= st1.countTokens()){
switch(tokenCount){
case 1:
String extra = st1.nextToken();
break;
case 2:
String Opp_transid = st1.nextToken();
pp_transid = strsplit(Opp_transid);
break;
case 3:
String Opp_respmsg = st1.nextToken();
pp_respmsg = strsplit(Opp_respmsg);
break;
case 4:
String Opp_authid = st1.nextToken();
pp_authid = strsplit(Opp_authid);
break;
case 5:
String Opp_avs = st1.nextToken();
pp_avs = strsplit(Opp_avs);
break;
case 6:
String Opp_avszip = st1.nextToken();
pp_avszip = strsplit(Opp_avszip);
break;
tokenCount++;
header.put("pp_transid", pp_transid);
header.put("pp_respmsg", pp_respmsg);
header.put("pp_authid", pp_authid);
header.put("pp_avs", pp_avs);
header.put("pp_avszip", pp_avszip);
}else{
newTag = new String(setVal.set_name(tag, issuedValue));
header.put(newTag, s);
//detail.put(newTag, s);
prod.put(newTag, s);
memInfo.put(newTag,s);
//Check to see-- if we should add this product to the database or not
boolean check = prod.checkValid(newTag, prodValue);
if (check){
prod.addValues(s);
setVal.clearMod();
==================================================================
Here's the error that i get:
java.util.NoSuchElementException
at org.apache.crimson.parser.Parser2.parseInternal(Parser2.java:691)
at org.apache.crimson.parser.Parser2.parse(Parser2.java:337)
at org.apache.crimson.parser.XMLReaderImpl.parse(XMLReaderImpl.java:448)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:345)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:281)
at Echo03.main(Echo03.java:47)I haven't gone through your code but I also had a similar error....and the exception in my was because of an "&" instead of the entity reference & in one of the element values. I use a non-validating parser but if you use a validating one then this might not be the reason for your exception.
Maybe you are looking for
-
I have an iPhone 4 and the iOS 4.3.5 download keeps failing. It downloads then I get a message stating that the download was corrupted and couldn't be installed. I've tried it with bitdefender switched off. I've tried it with it in airplane mode.
-
Buttons in panels that doent work..
hi all. im currently developing an application where panels are switched on a frame. each panel has its own actionlistener, and is working. the problem is that the buttons i create in a panel get a null value when an action event occurs. you can see
-
Hi What is the use of chapter id and when is it necessary to maintain chapter id for material. since with out maintaining chapterid i have created condition record of material for BED and other condition types and it worked in va01. I feel chapter
-
How do I get google out of my face?
I just installed LittleSnitch to find out what my Mac was sending when I wasn't actually doing anything on line. It seems to be forever communicating with google.... safebrowsing-cache.google.com or safebrowsing.clients.google.com. Anyone know why? I
-
Want to Learn Web page composer ?
Hi Experts, I want to learn Web Page composer ..... Can you please send me some documents or guide me in some way how can I start to learn Web Page Composer. Any Help will be appreciated. Thanks, Iqbal