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;

Similar Messages

  • Parsing an XML using DOM parser in Java in Recursive fashion

    I need to parse an XML using DOM parser in Java. New tags can be added to the XML in future. Code should be written in such a way that even with new tags added there should not be any code change. I felt that parsing the XML recursively can solve this problem. Can any one please share sample Java code that parses XML recursively. Thanks in Advance.

    Actually, if you are planning to use DOM then you will be doing that task after you parse the data. But anyway, have you read any tutorials or books about how to process XML in Java? If not, my suggestion would be to start by doing that. You cannot learn that by fishing on forums. Try this one for example:
    http://www.cafeconleche.org/books/xmljava/chapters/index.html

  • Problem in parsing an xml using DOM parser.

    Hi,
        I have created an action block for client.
        it  takes a xml file present on D drive and generates a pdf by parsing the xml file.
        My code was working perfectly fine till yesterday.
    But now i getting , [INFO ]: Error-- Premature end of file.  org.xml.sax.SAXParseException: Premature end of file.
    But xml is perfectly fine. Also the code work from eclipse.
    Need some inputs on this.
    Regards,
    Vishal Jadhav
    Edited by: vishal jadhav on Jan 23, 2009 9:49 AM

    Vishal,
    what exactly did you change? How do you call the action block? What version/Support package/Build of MII do you use?
    Have you see the following thread? There a user had the same message which was caused by missing credentials.
    [https://forums.sdn.sap.com/click.jspa?searchID=21364701&messageID=6756453]
    Michael
    Edited by: Michael Otto on Jan 23, 2009 11:57 AM

  • 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

  • Problem in parsing XML using DOM Parser.

    Hi,
    I am parsing an XML using DOM Parser.
    When i try to get attributes of a node, i dont get in the order it is written. For Eg. This the node:
    <Level0 label="News" link="/website/ing_news.nsf/ViewNewsForm?OpenForm&All" level="202" uid="COGN-4MNMT3" parentid="aaaa">
    When i try to print the attribute values i should get in the order:
    News, /website/ing_news.nsf/ViewNewsForm?OpenForm&All, 202, COGN-4MNMT3, aaaa
    BUT I AM GETTING IN THE ORDER:
    News, 202, /website/ing_news.nsf/ViewNewsForm?OpenForm&All, aaaa, COGN-4MNMT3
    Is there any way to sort this problem out?
    Thanks and Regards,
    Ashok

    Hi Guys,
    Thanks a lot for your replies.
    But i want to keep all the values as attributes only.
    the XML file is as shown below:
    <Menu>
    <Level0 label="News" link="/website/ing_news.nsf/ViewNewsForm?OpenForm&All" level="202" uid="COGN-4MNMT3" parentid="aaaa" children="3">
         <Level1 label="ING News" link="" level="1" uid="COGN-4MNN89" parentid="COGN-4MNMT3" children="3" >
              <Level2 label="All ING News" link="/website/ing_news.nsf/ViewNewsForm?OpenForm&All" level="2" uid="INGD-4MVTK2" parentid="COGN-4MNN89" children="0">
              </Level2>
    </Level1>
    </Level0>
    The code i was using to get attributes is:
    String strElementName = new String(node.getNodeName());
         // System.out.println("strElementName:"+node.getNodeName());
    NamedNodeMap attrs = node.getAttributes();
    if (attrs != null) {
    int iLength = attrs.getLength();
    for (int i = 0; i < iLength; i++) {
    String strAttributes = (String) attrs.item(i).getNodeName();
    String strValues = (String) attrs.item(i).getNodeValue();
    Also is it not possible to Enforce the order using some Schema/DTD in this case?
    TIA
    Ashok

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

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

  • 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

  • XML to CSV using SAX Parser

    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
    Thanks

    By 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

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

    SAX 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

  • How to use SAX parser in J2ME

    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

  • Issue in parsing an XML using kxml in Creme 4.1 JVM for WIndows CE

    Hi,
    I have written a code to parse an XML using KXML.jar.
    The code will read the XML file, parse the content and writes data to a text file.
    The code is working fine in normal Windows XP enviroment.
    The same code when tested in a pocket PC is not writing the content and also not throwing any error or exception.
    Please give me some inputs on how to resove this issue.
    TIA,
    shubakarthik

    Hi,
    I have written a code to parse an XML using KXML.jar.
    The code will read the XML file, parse the content and writes data to a text file.
    The code is working fine in normal Windows XP enviroment.
    The same code when tested in a pocket PC is not writing the content and also not throwing any error or exception.
    Please give me some inputs on how to resove this issue.
    TIA,
    shubakarthik

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

    You should ask in the Java forum.
    Regards
    Stefan

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

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

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

Maybe you are looking for