How do you store parsed XML data in an array

Hi, i am trying to complete a small program which implements the SAX parser to parse an XML file. My problem is that i am writing a custom class to store the parsed data into an array, and then make the array available to the main program via a simple method which returns the array. I know this must be very simple to do, but i seem to have developed a mental block with this part of the program. I can parse the data and print all the elements to the screen, but i just cant figure out how to store all the data elements into the array. I will post the class which is supposed to do this, and ask anyone out there if they know what i'm doing wrong, and also, if there is a more effeicient way of achieving this ( i expect there definitely is!! but i have never used the SAX parser before and am getting confused by the API docs on it!!) Any help very much appreciated.
Here is my attempt at coding the class to handle the parsed XML data
class Sink extends org.xml.sax.helpers.DefaultHandler
     implements org.xml.sax.ContentHandler{
Customer[] customers = new Customer[20];
     int count = 1;
     int x = 0;
     int tagCount = 0;
     String name;
String custID;
     String username;
     String address;
     String phoneNum;
public void startElement(String uri, String localName, String rawName, final org.xml.sax.Attributes attributes)throws org.xml.sax.SAXException{
//count the number of <name> tags in the XML file
     if(rawName.equals("name")){
          tagCount++;
public void characters(char[] ch, int start, int len){
//get the current string
     String text = new String(ch, start, len);
     String text1 = text.trim();
//there are 5 elements for each customer found in the XML file so when the count reaches 6
// i reset this to 1
     if(count == 6){
     count = count - 5;
     if(text1.length()>0 && count == 1){
          name = text1;
          System.out.println(name);
          }else{
     if(text1.length()>0 && count == 2){
          custID = text1;
          System.out.println(custID);
               }else{
               if(text1.length()>0 && count == 3){
               username = text1;
               System.out.println(username);
               }else{
                    if(text1.length()>0 && count == 4){
                    address = text1;
                    System.out.println(address);
                    }else{
                    if(text1.length()>0 && count == 5){
                         phoneNum = text1;
                         System.out.println(phoneNum);
                         //add data to the customer array
                         customers[x] = new Customer(name, custID, username, address, phoneNum);
// increment the array index counter
                    x = x+1;
                    }//end of if
                    }//end else
                    }//end else
               }//end else
          }//end else
}//end of characters method
public void endDocument(){
     System.out.println("There are " + tagCount +
     " <name> elements.");
}//end of class Sink
Before the end of this class i also need to make the array available to the calling program!!
Any help would be much appreciated
Thanks
Iain

Ok, yer going about this all the wrong way. You shouldn't have to maintain a count of all the elements. Basically you are locking yourself into the XML tags not only all being there but are assuming they are all in the same order. What you should do is in your characters() method, put all of the characters into a string buffer. Then, in endElement() (which you dont use btw, you should) you grab the information that is in the string buffer and store it into your Customer object depending on what the tagName is.
Also, you should probably use a List to store all the Customer objects and not an single array, it's more dynamic and you arent locked into a set number of Customers.
I wont do it all for you, but I'll give you a good outline to use.
public class CustomerHandler extends DefaultHandler {
    private java.util.List customerList;  // List of Customer objects
    private java.util.StringBuffer buf;   // StringBuffer to store the string of characters between the start and end tags
    private Customer customer;  // Customer object that is initialized with each entry.
    public CustomerHandler() {
        customerList = new java.util.ArrayList();   // Initialize the List
        buf = new java.util.StringBuffer();   // Initialize the string buffer
    //  Make your customer list available to other classes
    public java.util.List getCustomerList() {
        return customerList;
    public void startElement(String nsURI, String sName, String tagName, Attributes attributes) throws SAXException {
        // Clear the String Buffer
        //  If the tagName is "Customer" then create a new Customer object
    public void characters(char[] ch, int start, int length) {
        //  append the characters into the string buffer
    public void endElement(String nsURI, String sName, String tagName) throws SAXException {
        // If the tagName is "Customer" add your customer object to the List
        // Place the data from the String Buffer into a String
        //  Depending on the tagName, call the appropriate set method on your customer object
}

Similar Messages

  • How to store the XML data? file or database?

    i'm frustrate at it.
    If store XML data into files, then when i query any data,how can i search data using relationship as SQL?
    But if store XML data into database.How can i transform the xml data to the data table?
    Can any one give me an clear example.

    XML is perfect for data interchange and readability. However, to make it searchable you should resolve it properly into tables, in accordance of your own choice of model.
    1. Investigate the XML files and resolve the model
    <Person sex="male">John
    <Pet animal="dog">Doggy</Pet>
    <Pet animal="cat">Catty</Pet>
    </Person>
    2. Create the tables in your database, let one or several tables keep the raw xml for retrieval of original xml data.
    --- XMLDocument ---
    id XML_data
    --- Person ---
    id XML_Document_id sex name
    (foreign key)
    --- Pet ---
    id Person_id animal name
    (foreign key)
    3. Resolve data from the xml files and insert it into the database. Do this through your ContentHandler, or from your DOM model.
    --- XMLDocument ---
    id XML_data
    0 <Person>...</Person>
    --- Person ---
    id XML_Document_id sex name
    0 0 male John
    --- Pet ---
    id Person_id animal name
    0 0 dog Doggy
    1 0 cat Catty
    Gil

  • How to parsing xml data in sql statement??

    Hi friends, I have a table which contain column as clob ,stores in xml format, for example my column contain xml data like this
    <Employees xmlns="http://TargetNamespace.com/read_emp">
       <C1>106</C1>
       <C2>Harish</C2>
       <C3>1998-05-12</C3>
       <C4>HR</C4>
       <C5>1600</C5>
       <C6>10</C6>
    </Employees>
      Then how to extract the data in above xml column data using SQL statement...

    Duplicate post
    How to parsing xml data in sql statement??

  • How to parse xml data into java component

    hi
    everybody.
    i am new with XML, and i am trying to parse xml data into a java application.
    can anybody guide me how to do it.
    the following is my file.
    //MyLogin.java
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    class MyLogin extends JFrame implements ActionListener
         JFrame loginframe;
         JLabel labelname;
         JLabel labelpassword;
         JTextField textname;
         JPasswordField textpassword;
         JButton okbutton;
         String name = "";
         FileOutputStream out;
         PrintStream p;
         Date date;
         GregorianCalendar gcal;
         GridBagLayout gl;
         GridBagConstraints gbc;
         public MyLogin()
              loginframe = new JFrame("Login");
              gl = new GridBagLayout();
              gbc = new GridBagConstraints();
              labelname = new JLabel("User");
              labelpassword = new JLabel("Password");
              textname = new JTextField("",9);
              textpassword = new JPasswordField(5);
              okbutton = new JButton("OK");
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 1;
              gbc.gridy = 5;
              gl.setConstraints(labelname,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 2;
              gbc.gridy = 5;
              gl.setConstraints(textname,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 1;
              gbc.gridy = 10;
              gl.setConstraints(labelpassword,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 2;
              gbc.gridy = 10;
              gl.setConstraints(textpassword,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 1;
              gbc.gridy = 15;
              gl.setConstraints(okbutton,gbc);
              Container contentpane = getContentPane();
              loginframe.setContentPane(contentpane);
              contentpane.setLayout(gl);
              contentpane.add(labelname);
              contentpane.add(labelpassword);
              contentpane.add(textname);
              contentpane.add(textpassword);
              contentpane.add(okbutton);
              okbutton.addActionListener(this);
              loginframe.setSize(300,300);
              loginframe.setVisible(true);
         public static void main(String a[])
              new MyLogin();
         public void reset()
              textname.setText("");
              textpassword.setText("");
         public void run()
              try
                   String text = textname.getText();
                   String blank="";
                   if(text.equals(blank))
                      System.out.println("First Enter a UserName");
                   else
                        if(text != blank)
                             date = new Date();
                             gcal = new GregorianCalendar();
                             gcal.setTime(date);
                             out = new FileOutputStream("log.txt",true);
                             p = new PrintStream( out );
                             name = textname.getText();
                             String entry = "UserName:- " + name + " Logged in:- " + gcal.get(Calendar.HOUR) + ":" + gcal.get(Calendar.MINUTE) + " Date:- " + gcal.get(Calendar.DATE) + "/" + gcal.get(Calendar.MONTH) + "/" + gcal.get(Calendar.YEAR);
                             p.println(entry);
                             System.out.println("Record Saved");
                             reset();
                             p.close();
              catch (IOException e)
                   System.err.println("Error writing to file");
         public void actionPerformed(ActionEvent ae)
              String str = ae.getActionCommand();
              if(str.equals("OK"))
                   run();
                   //loginframe.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    hi, thanks for ur reply.
    i visited that url, i was able to know much about xml.
    so now my requirement is DOM.
    but i dont know how to code in my existing file.
    means i want to know what to link all my textfield to xml file.
    can u please help me out. i am confused.
    waiting for ur reply

  • Script for parsing xml data and inserting in DB

    Thank you for reading.
    I have the following example XML in an XML file. I need to write a script that can insert this data into an Oracle table. The table does not have primary keys. The data just needs to be inserted.
    I do not have xsd file in this scenario. Please suggest how to modify Method 1 https://community.oracle.com/thread/1115266?tstart=0 mentioned so that I can call the XML mentioned below and insert into a table
    Method 1
    Create or replace procedure parse_xml is 
      l_bfile   BFILE; 
      l_clob    CLOB; 
      l_parser  dbms_xmlparser.Parser; 
      l_doc     dbms_xmldom.DOMDocument; 
      l_nl      dbms_xmldom.DOMNodeList; 
      l_n       dbms_xmldom.DOMNode; 
      l_file      dbms_xmldom.DOMNodeList; 
      l_filen       dbms_xmldom.DOMNode; 
      lv_value VARCHAR2(1000); 
       l_ch      dbms_xmldom.DOMNode; 
    l_partname varchar2(100); 
    l_filename varchar2(1000); 
      l_temp    VARCHAR2(1000); 
      TYPE tab_type IS TABLE OF tab_software_parts%ROWTYPE; 
      t_tab  tab_type := tab_type(); 
    BEGIN 
      l_bfile := BFileName('DIR1', 'SoftwareParts.xml'); 
      dbms_lob.createtemporary(l_clob, cache=>FALSE); 
      dbms_lob.open(l_bfile, dbms_lob.lob_readonly); 
      dbms_lob.loadFromFile(dest_lob => l_clob,    src_lob  => l_bfile,    amount   => dbms_lob.getLength(l_bfile)); 
      dbms_lob.close(l_bfile);  
      dbms_session.set_nls('NLS_DATE_FORMAT','''DD-MON-YYYY'''); 
      l_parser := dbms_xmlparser.newParser; 
      dbms_xmlparser.parseClob(l_parser, l_clob); 
      l_doc := dbms_xmlparser.getDocument(l_parser); 
        dbms_lob.freetemporary(l_clob); 
      dbms_xmlparser.freeParser(l_parser); 
      l_nl := dbms_xslprocessor.selectNodes(dbms_xmldom.makeNode(l_doc),'/PartDetails/Part'); 
        FOR cur_emp IN 0 .. dbms_xmldom.getLength(l_nl) - 1 LOOP 
        l_n := dbms_xmldom.item(l_nl, cur_emp); 
        t_tab.extend; 
        dbms_xslprocessor.valueOf(l_n,'Name/text()',l_partname); 
        t_tab(t_tab.last).partname := l_partname; 
        l_file := dbms_xslprocessor.selectNodes(l_n,'Files/FileName'); 
        FOR cur_ch IN 0 .. dbms_xmldom.getLength(l_file) - 1 LOOP 
          l_ch := dbms_xmldom.item(l_file, cur_ch); 
          lv_value := dbms_xmldom.getnodevalue(dbms_xmldom.getfirstchild(l_ch)); 
          if t_tab(t_tab.last).partname is null then t_tab(t_tab.last).partname := l_partname; end if; 
          t_tab(t_tab.last).filename := lv_value; 
        t_tab.extend; 
       END LOOP; 
       END LOOP; 
        t_tab.delete(t_tab.last); 
      FOR cur_emp IN t_tab.first .. t_tab.last LOOP 
      if t_tab(cur_emp).partname is not null and  t_tab(cur_emp).filename is not null then 
        INSERT INTO tab_software_parts 
        VALUES 
        (t_tab(cur_emp).partname, t_tab(cur_emp).filename); 
        end if; 
      END LOOP; 
      COMMIT; 
      dbms_xmldom.freeDocument(l_doc); 
    EXCEPTION 
      WHEN OTHERS THEN 
        dbms_lob.freetemporary(l_clob); 
        dbms_xmlparser.freeParser(l_parser); 
        dbms_xmldom.freeDocument(l_doc); 
    END; 
    <TWObject className="TWObject">
      <array size="240">
        <item>
          <variable type="QuestionDetail">
            <questionId type="String"><![CDATA[30]]></questionId>
            <questionType type="questionType"><![CDATA[COUNTRY]]></questionType>
            <country type="String"><![CDATA[GB]]></country>
            <questionText type="String"><![CDATA[Please indicate]]></questionText>
            <optionType type="String"><![CDATA[RadioButton]]></optionType>
            <answerOptions type="String[]">
              <item><![CDATA[Yes]]></item>
              <item><![CDATA[No]]></item>
            </answerOptions>
            <ruleId type="String"><![CDATA[CRP_GB001]]></ruleId>
            <parentQuestionId type="String"></parentQuestionId>
            <parentQuestionResp type="String"></parentQuestionResp>
          </variable>
        </item>
        <item>
          <variable type="QuestionDetail">
            <questionId type="String"><![CDATA[40]]></questionId>
            <questionType type="questionType"><![CDATA[COUNTRY]]></questionType>
            <country type="String"><![CDATA[DE]]></country>
            <questionText type="String"><![CDATA[Please indicate]]></questionText>
            <optionType type="String"><![CDATA[RadioButton]]></optionType>
            <answerOptions type="String[]">
              <item><![CDATA[Yes]]></item>
              <item><![CDATA[No]]></item>
            </answerOptions>
            <ruleId type="String"><![CDATA[CRP_Q0001]]></ruleId>
            <parentQuestionId type="String"></parentQuestionId>
            <parentQuestionResp type="String"></parentQuestionResp>
          </variable>
        </item>
      </array>
    </TWObject>

    Reposted as
    Script to parse XML data into Oracle DB

  • HT4847 How do you store apps in icloud

    How do you store apps in the Icloud??

    By either restoring your iCloud backup, which will restore all data, settings, apps and other purchased media contained in the backup, or by redownloading them from the app store as discussed here: http://support.apple.com/kb/ht2519 (which will restore the app, but not any app data).

  • How Do You Store Your Movie Masters?

    Hi all,
    I'm curious, how do you store your Movie Masters? Let's say you filmed an important Family event from a camcorder with a hard drive. You imported the footage into you mac and edited it in iMovie or Final Cut Pro or other app.
    Then what?
    Do you make a DVD?
    Do you save a DVD image file on the computer?
    Do you export a .mov or other format file?
    Do you delete the DV original files because they are so massive?
    Do you save/delete the iMovie or FCP master original footage?
    When do you delete the camcorder hard drive original (when you need the space)?
    What other approaches do you do?
    Which is the Master?
    How do you back up your movie?
    Thanks in advance for your opinions.

    Great question. I think the issue of backup is a important one, and one I always worry about since I have a lot of video footage that is irreplaceable.
    For back-up, it is helpful to define the risk you are trying to protect from.
    For example,
    1) risk of corruption in iMovie --> I might use Time Machine (but I do not because I have not had the issue)
    2) risk of hard drive failure --> I use SuperDuper! nightly
    3) Risk of theft or fire --> offsite backup
    Here is what I do...
    1) I back up my boot disk with SuperDuper automatically to alternate external partitions every other night so I always have two bootable systems. One is less than one day old, and one is less than two days old.
    2) I back up my original video files. For my Motion JPEG, VHS-->AIC, DV, and 8MM to DV, the EVENT is the copy I back up. For my AVCHD high def video, I back up the archive of the AVCHD, but I am not currently backing up the Event files, because I would need from 4 to 8 TB to back up these events depending on whether I made one copy or two.
    3) I use CrashPlan for my offsite backup. It costs less than $4 per month, and I seeded the initial backup to an external drive to minimize having to transfer video files over the Internet. I currently have 1.2TB of data backed up to CrashPlan, which includes my entire boot drive, and the files described in #2.
    4) All of the above is automated, so I don't have to think about it too much. If I have to manually do stuff, I tend to get behind.
    You have to consider the value of total multiple redundancy vs. the likelihood that 2 or three unlikely events would all happen at once. For example, CrashPlan could lose my data. My hard disk could fail. I could lose everything in a fire. But it is unlikely that they would all happen at once, except in nuclear war, in which case, who cares?
    I am considering adding Time Machine backup and some off-site backup of the Event files into the mix, but for now I am satisfied.

  • How do you remove back up data from the memory storage? my storage data states that i have over 80gb of data used for back ups and i dont know why as i use a external hard drive as a time machine .now my 250gb flash storage is nearly full

    how do you remove back up data from the memory storage? my storage data states that i have over 80gb of data used for back ups and i dont know why as i use a external hard drive as a time machine .now my 250gb flash storage is nearly full.. HELP!

    When Time Machine backs up a portable Mac, some of the free space will be used to make local snapshots, which are backup copies of recently deleted files. The space occupied by local snapshots is reported as available by the Finder, and should be considered as such. In the Storage display of System Information, local snapshots are shown as  Backups. The snapshots are automatically deleted when they expire or when free space falls below a certain level. You ordinarily don't need to, and should not, delete local snapshots yourself. If you followed bad advice to disable local snapshots by running a shell command, you may have ended up with a lot of data in the Other category. Ask for instructions in that case.
    See this support article for some simple ways to free up storage space.

  • How do you edit out the date and time stamp from a photo

    How do you edit out the date and time stamp from a photo

    You can blur it out with retouch
    The built-in "Retouch" brush in "Edit" mode should suffice, if the background is mostly uniform, and if you set the size of the brush to slightly wider than the bar width of the letters. For example, in this picture I removed the year from the date (in the lower right corner) by using the "retouch" brush and following the contours of the letters. (the screen shot is from iPhoto '11, but iPhoto 9 should give similar results).
    Regards
    Léonie

  • How to Read and Write .XML datas   (HELP Plz...)

    hai everybody
    how to read and write xml datas... plz give clean and simple example..
    bcoz me want to produce such type of module...
    if any one help me .. thats the only way me laid in software ladder
    plz....
    thank u in advance

    thank u for giving idiot..
    but before posting i search in google also..
    but i cant get what me expect..
    thus i posted...
    then who is ................?
    sorry javacoder01
    // plz help me
    Message was edited by:
    drvijayy2k2

  • How do you restore the "Last Date Played" notice in the iTunes window for songs?

    How do you restore the "Last Date Played" note in the iTunes window of playlists?  I lost this a couple of weeks ago, and had someone explain the steps to take (which are not on the iTunes "Help" menu).  Thanks.

    In the playlist, Right Mouse click on the column headers and it will give you a list to choose from in the pop up select Last Played and that column will display

  • How do you differentiate IDOC XML format and ordinary XML format

    how do you differentiate IDOC XML format and ordinary XML format since they are used by IDOC adapter and RFC adapter???

    Hi,
    Cremas Structure starts with Header and followed by Segments...
    Normally it begins like this
    <CREMAS03><IDOC BEGIN="1">
    The second node is Idoc in the header..
    Thanks
    Anju

  • How could we read the XML data from a table using BODS.

    Hi Guys,
    My requirement is , As the OLTP system  consists of a table called person which consists of a column demographics. so how could i read this XML data which is in one column of an SQL table called persons. As this XML data will populate the remaining fields in my target using BODS.
    Regards,
    Amjad.

    Hi Amjad,
    I am afraid there ain't any direct method to extract XML field from a data base.
    Indirect way could be converting the whole table (instead of one field) into XML format and then extract one field from it!!
    Regards,
    Mubashir Hussain

  • How would you store a primitive type?

    Hello
    How would you store a primitive type in a Collection such as a List?
    Thanks
    Bobby

    <face grin=evil> myList.add(int.class); </face>

  • How do you store books

    How do you store books on iPads?

    Books from where, and I'm not sure what you mean by store (?).  Most ebooks have digital rights management on them which tie them to the store's own apps/ereaders, so ibooks from Apple can only be read in the iBooks app, and ebooks from Amazon can only be read in their Kindle apps and Kindle ereaders. You can download ibooks from Apple directly in the iBooks app via the Store button at the top left of the bookshelf in the app, and similarly other abook apps generally allow you to download purchases from their store directly in them. The iBooks app also supports DRM-free epub books (e.g. books from project Gutenberg etc) which you can either use 'open in' on Safari to copy them to iBooks, or you can download them on your computer, add to its iTunes (File > Add To Library) and then sync to the iBooks app via the iPad device's Books tab.
    You can copy ibooks/epubs/PDFs from the iBooks app to your computer's iTunes via File > Transfer Purchases for backup and future re-syncing.

Maybe you are looking for

  • How can I update programs that were purchased for me?

    I received a laptop that was preloaded with Final Cut Pro and Motion. I have updated the OS to 10.9.1 and when I try to install upates for FCP and Motion I get the Apple ID for the person who installed the original programs and no way to change it to

  • Posterior Data Corrections

    I have a business objects related problem, or a business process issue depending on how you look at it. The issue is that we currently have a process by which results from one system that are automatically generated need to undergo some post-processi

  • Using MBA 11 with VGA adaptor

    I have just replaced my ageing, white iBook G4 with a MBA 11. Most of my time is spent hauling this faithful old trooper all over town and giving presentations by plugging it into all sorts of VGA projectors and/or big LCD/Plasma screens, so I decide

  • JCO difference between SAP J2ee 620 and Webas 640 for Internet Sales

    Does anyone have some information on how Internet Sales manages JCO calls to R/3 or CRM on WebAS 640? Till J2EE 620 the sapjco.jar file directory had to be in classpath along with the relevant dlls in WinNt directory. WebAs 640 Java installation does

  • HSM Vendor and cost information?

    Hi All, Can you help me get answer for below questions- Who is/are the vendor to purchase the HSM hardware? Please let me kkow if you are aware of cost information? Edited by: Vinayak C on Oct 5, 2012 5:17 AM