SAX parser retrieve attribute
Hi, I am parsing using the SAX Parser. In the XML excerpt below, how do I retrieve the "POL", "SUM" or "EUR" values?
If I use a contenthandler and I can extract the SubjectCode, Subject, and SubjectQualifier element names, but not the data contained within the attributes.
Thanks in advance fo rthe help...
<SubjectCode>
<Subject FormalName="POL"/>
<SubjectQualifier FormalName="SUBJECT"/>
<Subject FormalName="SUM"/>
<SubjectQualifier FormalName="SUBJECT"/>
<Subject FormalName="EUR"/>
<SubjectQualifier FormalName="SUBJECT"/>
<Subject FormalName="GER"/>
<SubjectQualifier FormalName="COUNTRY"/>
<Subject FormalName="ITA"/>
<SubjectQualifier FormalName="COUNTRY"/>
<Subject FormalName="USA"/>
<SubjectQualifier FormalName="COUNTRY"/>
</SubjectCode>
Something like this:public void startElement(String uri, String localName, String qName, Attributes attributes) {
if (localName.equals("Subject")) {
String formalName = attributes.getValue("FormalName");
// do something with that string
// and so on
}
Similar Messages
-
Question on SAX Parser: retrieving child
Hi,
I am using SAX parser to parse the XML file, because the XML file size are huge. But here i need to retrieve the child nodes of the element. Is it possible with SAX parser to retrieve the child nodes? (Like DOM parser getChildNodes method)
Thanks in advance.No, of course not. When you use SAX you write the code that stores the information. So if you need the child nodes, then write code that collects all child nodes.
-
Error processing request in sax parser No 'action' attribute found in XML
Hi All,
I am doing a FILE to JDBC Scenario. I just want to send a data from file to Sql Db table. For this I have written a stored procedure to insert the row in a table.
This is the message mapping for FILE to JDBC .
Sender Receiver
*FILESENDER_MT 1..1 FILESENDER_DT * SPRECEIVER_MT 1..1
.NO 1..1 xsd:string * Statement 1..1 string
.Name 1..1 xsd:string *user_PROC 1..1
action 1..1required
*No
isInput 1..1 string
type 1..1 string
*Name
isInput 1..1 string
type 1..1 string
Mapped Values....
Statement is mapped with <b>FILESENDER_MT</b>
action attribute is mapped with "<b>EXECUTE</b>" Constant
No is mapped with <b>NO</b>
Name is mapped with <b>Name</b>
for both isInput is mapped with <b>TRUE</b>
for both type is mapped with <b>CHAR</b>
Here is the my stored procedure.....
CREATE PROCEDURE [dbo].[user_PROC]
@NO char(10), @Name char(10) AS
insert into FILE2JDBC values('a','ab')
GO
when i run this stored procedure in Sql directly it was executed successfully....
I have checked In SXMB_MONI status is showing green...
xml messages from SXMB_MONI ....
this is the message from payloads of Inbound Message
<PRE> <?xml version="1.0" encoding="UTF-8" ?>
- <ns0:FILESENDER_MT xmlns:ns0="http://www.prospectadelhi.com/DELHI_FILE2JDBC">
<NO>111</NO>
<NAME>murthy</NAME>
</ns0:FILESENDER_MT></PRE>
this is the message from payloads of Request Message Mapping
<?xml version="1.0" encoding="UTF-8" ?>
- <ns0:SPRECEIVER_MT xmlns:ns0="http://www.prospectadelhi.com/DELHI_FILE2JDBC">
- <Statement>
- <user_PROC>
<action>EXECUTE</action>
- <NO>
<isInput>TRUE</isInput>
<type>CHAR</type>
</NO>
- <Name>
<isInput>TRUE</isInput>
<type>CHAR</type>
</Name>
</user_PROC>
</Statement>
</ns0:SPRECEIVER_MT>
this is the error showing in runtime workbench>component monitoring->communication channel monitoring-->Receiver Communication Channel....
<b>Error while parsing or executing XML-SQL document: Error processing request in sax parser: No 'action' attribute found in XML document (attribute "action" missing or wrong XML structure)</b>
Can any body tell me whether the problem is in Mapping or in Data Type Structure..
Please resolve this issue....
Thanks in Advance,
Murthy.<?xml version="1.0" encoding="UTF-8" ?>
- <ns0:SPRECEIVER_MT xmlns:ns0="http://www.prospectadelhi.com/DELHI_FILE2JDBC">
- <Statement>
<b>- <user_PROC>
<action>EXECUTE</action></b>
- <NO>
<isInput>TRUE</isInput>
<type>CHAR</type>
</NO>
- <Name>
<isInput>TRUE</isInput>
<type>CHAR</type>
</Name>
</user_PROC>
</Statement>
</ns0:SPRECEIVER_MT>
The Action should be a Attribute of Element user_Proc as,
<?xml version="1.0" encoding="UTF-8" ?>
- <ns0:SPRECEIVER_MT xmlns:ns0="http://www.prospectadelhi.com/DELHI_FILE2JDBC">
- <Statement>
<b>- <user_PROC action="Execute"></b>- <NO>
<isInput>TRUE</isInput>
<type>CHAR</type>
</NO>
- <Name>
<isInput>TRUE</isInput>
<type>CHAR</type>
</Name>
</user_PROC>
</Statement>
</ns0:SPRECEIVER_MT>
Likewise isInput and Type should be Attributes and not Elements .
Regards
Bhavesh -
Exiting from SAX parser on finding specific element/attribute
Is there a way to return/exit from a SAX parser as soon as I get my search element the first time, without parsing the whole XML file?
Please let me know.
ThanksThanks for the information, but what I am exactly looking for is to only return back from SAX parser to the calling program.
System.exit(0) shuts down the whole application.
please let me know -
How to deal with empty tags in a SAX Parser
Hi,
I hope someone can help me with the problem I am having!
Basically, I have written an xml-editor application. When an XML file is selected, I parse the file with a SAX parser and save the start and end locations of all the tags and character data. This enables me to display the xml file with the tags all nicely formatted with pretty colours. Truly it is a Joy To Behold. However, I have a problem with tags in this form:
<package name="boo"/>
because the SAX parser treats them like this:
<package name = boo>
</package>
for various complex reasons the latter is unaccetable so my question is: Is there some fiendishly clever method to detect tags of this type as they occur, so that I can treat them accordingly?
Thanks,
ChrisI have spent some time on googling for code doing this, but found nothing better, than I had to write in by myself.
So, it would be something like this. Enjoy :)
package comd;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.SAXException;
import org.xml.sax.Attributes;
import java.util.Stack;
import java.util.Enumeration;
public class EmptyTagsHandler extends DefaultHandler {
private StringBuilder xmlBuilder;
private Stack<XmlElement> elementStack;
private String processedXml;
private class XmlElement{
private String name;
private boolean isEmpty = true;
public XmlElement(String name) {
this.name = name;
public void setNotEmpty(){
isEmpty = false;
public EmptyTagsHandler(){
xmlBuilder = new StringBuilder();
elementStack = new Stack();
private String getElementXPath(){
StringBuilder builder = new StringBuilder();
for (Enumeration en=elementStack.elements();en.hasMoreElements();){
builder.append(en.nextElement());
builder.append("/");
return builder.toString();
public String getXml(){
return processedXml;
public void startDocument() throws SAXException {
xmlBuilder = new StringBuilder();
elementStack.clear();
processedXml = null;
public void endDocument() throws SAXException {
processedXml = xmlBuilder.toString();
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (!elementStack.empty()) {
XmlElement elem = elementStack.peek();
elem.setNotEmpty();
xmlBuilder.append("<");
xmlBuilder.append(qName);
for (int i=0; i<attributes.getLength();i++){
xmlBuilder.append(" ");
xmlBuilder.append(attributes.getQName(i));
xmlBuilder.append("=");
xmlBuilder.append(attributes.getValue(i));
xmlBuilder.append(">");
elementStack.push(new XmlElement(qName));
public void endElement(String uri, String localName, String qName) throws SAXException {
XmlElement elem = elementStack.peek();
if (elem.isEmpty) {
xmlBuilder.insert(xmlBuilder.length()-1, "/");
} else {
xmlBuilder.append("</");
xmlBuilder.append(qName);
xmlBuilder.append(">");
elementStack.pop();
public void characters(char ch[], int start, int length) throws SAXException {
if (!elementStack.empty()) {
XmlElement elem = elementStack.peek();
elem.setNotEmpty();
String str = new String(ch, start, length);
xmlBuilder.append(str);
public void ignorableWhitespace(char ch[], int start, int length) throws SAXException {
String str = new String(ch, start, length);
xmlBuilder.append(str);
} -
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 -
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? -
How to Create XML file with SAX parser instead of DOM parser
HI ALL,
I am in need of creating an XML file by SAX parser ONLY. As far as my knowledge goes, we can use DOM for such purpose(by using createElement, creatAttribute ...). Can anyone tell me, is there any way to create an XML file using SAX Parser only. I mean, I just want to know whether SAX provides any sort of api for Creatign an element, attribute etc. I know that SAX is for event based parsing. But my requirement is to create an XML file from using only SAX parser.
Any help would be appreciated
Thanx in advance
KaushikHi,
You must write a XMLWriter class yourself, and that Class extends DefaultHandle ....., the overwrite the startElement(url, localName, qName, attributeList), startDocument(), endElement().....and so on.
in startElement write your own logic about how to create a new element and how to create a Attribute list
in startDocument write your own logic about how to build a document and encodeType, dtd....
By using:
XMLWriter out = new XMLWriter()
out.startDocument();
Attribute attr1 = new Atribute();
attr1.add("name", "value");
out.startElement("","","Element1", attr1);
Attribute attr2 = new Atribute();
attr2.add("name", "value");
out.startElement("","","Element2", attr2);
out.endElement("","","Element2");
out.endElement("","","Element1");
out.endDocument(); -
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.
-
JDBC receiver adapter - Error processing request in sax parser
Hello,
I want to INSERT idoc data via JDBC adapter into a MS SQL database. After digging through SAP Help, numerous blogs and forum discussions on SDN and even posting an OSS message I still get the same error:
'Error: TransformException error in xml processor class: Error processing request in sax parser: No 'action' attribute found in XML document (attribute "action" missing or wrong XML structure)'
When testing my mapping in the Integration Repository the resulting XML message is:
<?xml version="1.0" encoding="UTF-8"?>
<ns0:Employee xmlns:ns0="http://prodrive.nl/xi/HRMasterdata/HRMD_A_2_d_bcommerp">
<STATEMENT>
<T_PD_Employees action="INSERT">
<access>
<KeyTag>00088888</KeyTag>
<PerNo>00088888</PerNo>
</access>
</T_PD_Employees>
</STATEMENT>
</ns0:Employee>
The connection to the database is fine, Sender adapter with a SELECT * works perfect.
Can anyone help me solve this problem? I'm lost.
Best regards,
Roelof Jan BouwknegtHi Bhavesh,
I have tried out the change you suggested. Without success. Message I get back is
- 2006-12-28 10:34:08 CET: Error: TransformException error in xml processor class: Error processing request in sax parser: No 'action' attribute found in XML document (attribute "action" missing or wrong XML structure)
structure in testtool:
<?xml version="1.0" encoding="UTF-8"?>
<ns0:Employee xmlns:ns0="http://prodrive.nl/xi/HRMasterdata/HRMD_A_2_d_bcommerp">
<STATEMENT>
<T_PD_Employees action="INSERT">
<ACCESS>
<KEYTAG>00088888</KEYTAG>
<PERNO>00088888</PERNO>
</ACCESS>
</T_PD_Employees>
</STATEMENT>
</ns0:Employee>
Somehow the SAX parser doesn't like the result of my mapping. Maybe there is something wrong with the structure cardinality. Let me describe what I have built:
XSD:
WA_T_PD_Employees - Complex Type
> STATEMENT - Element - Occurence = 1
>> T_PD_Employees - Element - Occurence = 1
>>> STATEMENT - Attribute - Occurence = optional
>>> access - Element - Occurence = 1..Unbounded
Best regards Roelof Jan and thanks for your quick response -
How to get a specific tag value from SAX parser
I am using the SAX method to parse my xml file.
My Question is how to get the returning characters parsed after calling?
esp the value of <body> tag?
Here is my xml file, and i want to get the parsed <body> value after call sax parser.
<?xml version="1.0" encoding="UTF-8"?>
<article>
<content>
<title>floraaaaa</title>
<date>2004-03-19</date>
<body>
Details of an article, and i want to get the article details
</body>
</content>
</article>here is the parser code I am using:
import java.io.*;
import org.apache.xerces.parsers.SAXParser;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.ErrorHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
public class test2 {
public String m_xmlDetail;
public void readDetail(String url) {
System.out.println("Parsing XML File: " + url + "\n\n");
try {
XMLReader parser = new SAXParser();
ContentHandler contentHandler = new MyContentHandler();
parser.setContentHandler(contentHandler);
parser.parse(url);
} //try ends here
catch (IOException e) {
System.out.println("Error reading URI: " + e.getMessage());
} //catch ends here
catch (SAXException e) {
System.out.println("Error in parsing: " + e.getMessage());
} //catch ends here
} //function
}//close class
public class MyContentHandler implements ContentHandler {
private Locator locator;
//public String m_bodyDetail=new String();
public void setDocumentLocator(Locator locator) {
System.out.println(" * setDocumentLocator() called");
this.locator = locator;
public void startDocument() throws SAXException {
System.out.println("Parsing begins...");
public void endDocument() throws SAXException {
System.out.println("...Parsing ends.");
public void processingInstruction(String target, String data)throws SAXException {
System.out.println("PI: Target:" + target + " and Data:" + data);
public void startPrefixMapping(String prefix, String uri) {
System.out.println("Mapping starts for prefix " + prefix + " mapped to URI " + uri);
public void endPrefixMapping(String prefix) {
System.out.println("Mapping ends for prefix " + prefix);
public void startElement(String namespaceURI, String localName,String rawName, Attributes atts)throws SAXException {
System.out.print("startElement: " + localName);
if (!namespaceURI.equals("")) {
System.out.println(" in namespace " + namespaceURI + " (" + rawName + ")");
else {
System.out.println(" has no associated namespace");
for (int i=0; i<atts.getLength(); i++)
System.out.println(" Attribute: " + atts.getLocalName(i) +"=" + atts.getValue(i));
public void endElement(String namespaceURI, String localName, String rawName) throws SAXException {
System.out.println("endElement: " + localName + "\n");
public void characters(char[] ch, int start, int end) throws SAXException {
String s = new String(ch, start, end);
System.out.println("characters: " + s);
public void ignorableWhitespace(char[] ch, int start, int end)throws SAXException {
String s = new String(ch, start, end);
System.out.println("ignorableWhitespace: [" + s + "]");
public void skippedEntity(String name) throws SAXException {
System.out.println("Skipping entity " + name);
} //close class -
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;
} -
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 -
SAX parser doesn't report IDREF type
I have been trying to create my first DTD:
<!ELEMENT Network (Node+, Link*)>
<!ELEMENT Node EMPTY>
<!ATTLIST Node
ID ID #REQUIRED
title CDATA #IMPLIED>
<!ELEMENT Link EMPTY>
<!ATTLIST Link
source IDREF #REQUIRED
dest IDREF #REQUIRED
title CDATA #IMPLIED>
and would expect that the source and dest attributes of the
Link element would have the type IDREF when being parsed with
the SAX parser. Using the SAXSample.java provided I get the
following output for a test network:
StartElement:Network
IgnorableWhiteSpace
StartElement:Node
ID(ID)=node1
title(CDATA)=test node
EndElement:Node
IgnorableWhiteSpace
StartElement:Node
ID(ID)=node2
title(CDATA)=another node
EndElement:Node
IgnorableWhiteSpace
StartElement:Link
source(CDATA)=node2
dest(CDATA)=node1
EndElement:Link
IgnorableWhiteSpace
StartElement:Link
source(CDATA)=node1
dest(CDATA)=node2
EndElement:Link
IgnorableWhiteSpace
EndElement:Network
This clearly shows source and dest reported as CDATA type. Not
exactly what's in the DTD.
Is this an undocumented feature (a.k.a. bug?)
Regards,
Gary Howard.
Smart Network Technology,
Nortel Networks, UK
nullThanks for the replies, but I don't think we are quite connecting. I do eventually want to be able to validate an XML file against a schema (which I can't do either), but first I want to be able to validate the schema file itself; i.e. to confirm that the schema I designed is a valid schema file. As I understand it, it should be possible to tell the parser that the schema to validate against is the "schema for writing schemas", http://www.w3.org/Schema/schema.xsd (or whatever it is). That's where I'm getting stuck, that the parser doesn't recognize the elements for actually defining a schema.
-
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
Maybe you are looking for
-
Could anyone advise me on how I can use iWeb on different computers to update my website. Currently I used IWeb on my iMac, but I would like to be able to update my website using iWeb on my MacBook Air, I could not find a way to make it happen, tried
-
Hi, Could someone suggest a way to delete email Ids from Vendor MAster enmasse. Tried LSMW via XK02 recording but doesn't display the communication data. any help is much appreciated.
-
Want to see constant value of CPU not the aggregated one from the cube?
Hi All, When I see my layout with fiscyear ,it shows the aggregated values for Quantity,Cost Per Unit,0Amount,which is distributed across period. For example if one WBS and one uear(2008) -0Quantity(12),CPU(100) to four periods of one fiscyear.The di
-
Why is 3D acceleration with nouveau so much discouraged?
From nouveau wiki: Any 3-D functionality that might exist is still unsupported. Do not ask for instructions to try it. From archwiki: If you want to try 3D acceleration or you have problems with it, you are on your own, unless you are looking to cont
-
WRONG ADDRESS AND DUPLICATE BILLING
I am sick and tired of BT. I honestly wish that I would have gone with an alternative provider for both line and broadband. After informing them that I had moved house (provided new address) and said I wanted my old line cancelled and a new line put