Parse a Date to String

Hi
i would use this to parse String to Date :
public Date parseFromString(String dateString){
      try {
          java.text.SimpleDateFormat formatter
              = new java.text.SimpleDateFormat("dd/MM/yy");
          return formatter.parse(dateString);
      catch (Exception e) {
      return null;
  }how can i parse a Date to string?
Thanks
D

check the API Docs for SimpleDateFormat - particularly the format method. public StringFormatFromDate(Date date){
      try {
          java.text.SimpleDateFormat formatter
              = new java.text.SimpleDateFormat("dd/MM/yy");
          return formatter.format(date);
      catch (Exception e) {
           // You really shouldn't catch Exception - and you really should do something in your catch
           // blocks so you don't post a question like "my code executes no problem, but nothing happens...
           e.printStackTrace();
      return null;
  }

Similar Messages

  • Parse/seperate data from string

    I have a string that is returned from Google GeoCoding:
    {   "name": "193 Farrow Hill Road,Davisville,WV",   "Status": {     "code": 200,     "request": "geocode"   },   "Placemark": [ {     "id": "p1",     "address": "Davisville, WV, USA",     "AddressDetails": {    "Accuracy" : 4,    "Country" : {       "AdministrativeArea" : {          "AdministrativeAreaName" : "WV",          "SubAdministrativeArea" : {             "Locality" : {                "LocalityName" : "Davisville"             },             "SubAdministrativeAreaName" : "Wood"          }       },       "CountryName" : "USA",       "CountryNameCode" : "US"    } },     "ExtendedData": {       "LatLonBox": {         "north": 39.2357655,         "south": 39.1665921,         "east": -81.4344257,         "west": -81.5624851       }     },     "Point": {       "coordinates": [ -81.4984554, 39.2011873, 0 ]     }   } ] }
    I want to be able to parse this data into variables that I can use and update a table.
    I currently use ListGetAt() function and try to find common delimiters to narrow down what I am trying to parse, but this processes does not always return the results I am needing.
    Does anyone know of any faster more robust way of parsing this string down to variables? And, it could be that I am not using the ListGetAt() to its full potential as well....
    What I need most out of this string is in bold below...you'll notice different string lengths depending on if it recognizes the street address or not.
    This is the string returned if it DOES NOT recognize the street address:
    {   "name": "193 Farrow Hill Road,Davisville,WV",   "Status": {     "code": 200,     "request": "geocode"   },   "Placemark": [ {     "id": "p1",     "address": "Davisville, WV, USA",     "AddressDetails": {    "Accuracy" : 4,    "Country" : {       "AdministrativeArea" : {          "AdministrativeAreaName" : "WV",          "SubAdministrativeArea" : {             "Locality" : {                "LocalityName" : "Davisville"             },             "SubAdministrativeAreaName" : "Wood"          }       },       "CountryName" : "USA",       "CountryNameCode" : "US"    } },     "ExtendedData": {       "LatLonBox": {         "north": 39.2357655,         "south": 39.1665921,         "east": -81.4344257,         "west": -81.5624851       }     },     "Point": {       "coordinates": [ -81.4984554, 39.2011873, 0 ]     }   } ] }
    This is the string returned if it DOES recognize the street address:
    {   "name": "W7499 So. Mound Rd,Neillsville,WI",   "Status": {     "code": 200,     "request": "geocode"   },   "Placemark": [ {     "id": "p1",     "address": "S Mound Rd, Neillsville, WI 54456, USA",     "AddressDetails": {    "Accuracy" : 6,    "Country" : {       "AdministrativeArea" : {          "AdministrativeAreaName" : "WI",          "SubAdministrativeArea" : {             "Locality" : {                "LocalityName" : "Neillsville",                "PostalCode" : {                   "PostalCodeNumber" : "54456"                },                "Thoroughfare" : {                   "ThoroughfareName" : "S Mound Rd"                }             },             "SubAdministrativeAreaName" : "Clark"          }       },       "CountryName" : "USA",       "CountryNameCode" : "US"    } },     "ExtendedData": {       "LatLonBox": {         "north": 44.5921279,         "south": 44.5858326,         "east": -90.5981846,         "west": -90.6802503       }     },     "Point": {       "coordinates": [ -90.6394276, 44.5889072, 0 ]     }   }, {     "id": "p2",     "address": "S Mound Rd, Neillsville, WI 54456, USA",     "AddressDetails": {    "Accuracy" : 6,    "Country" : {       "AdministrativeArea" : {          "AdministrativeAreaName" : "WI",          "SubAdministrativeArea" : {             "Locality" : {                "LocalityName" : "Neillsville",                "PostalCode" : {                   "PostalCodeNumber" : "54456"                },                "Thoroughfare" : {                   "ThoroughfareName" : "S Mound Rd"                }             },             "SubAdministrativeAreaName" : "Clark"          }       },       "CountryName" : "USA",       "CountryNameCode" : "US"    } },     "ExtendedData": {       "LatLonBox": {         "north": 44.5920678,         "south": 44.5857725,         "east": -90.6802503,         "west": -90.7004168       }     },     "Point": {       "coordinates": [ -90.6899796, 44.5889209, 0 ]     }   } ] }

    That is indeed JSON, as Jochem says. You can pick out data using structs and arrays. You will know which structure or array functionality to use after doing something like this
    <cfsavecontent variable="myJSON1">
    {   "name": "193 Farrow Hill Road,Davisville,WV",   "Status": {     "code": 200,     "request": "geocode"   },   "Placemark": [ {     "id": "p1",     "address": "Davisville, WV, USA",     "AddressDetails": {    "Accuracy" : 4,    "Country" : {       "AdministrativeArea" : {          "AdministrativeAreaName" : "WV",          "SubAdministrativeArea" : {             "Locality" : {                "LocalityName" : "Davisville"             },             "SubAdministrativeAreaName" : "Wood"          }       },       "CountryName" : "USA",       "CountryNameCode" : "US"    } },     "ExtendedData": {       "LatLonBox": {         "north": 39.2357655,         "south": 39.1665921,         "east": -81.4344257,         "west": -81.5624851       }     },     "Point": {       "coordinates": [ -81.4984554, 39.2011873, 0 ]     }   } ] }
    </cfsavecontent>
    <cfsavecontent variable="myJSON2">
    {   "name": "W7499 So. Mound Rd,Neillsville,WI",   "Status": {     "code": 200,     "request": "geocode"   },   "Placemark": [ {     "id": "p1",     "address": "S Mound Rd, Neillsville, WI 54456, USA",     "AddressDetails": {    "Accuracy" : 6,    "Country" : {       "AdministrativeArea" : {          "AdministrativeAreaName" : "WI",          "SubAdministrativeArea" : {             "Locality" : {                "LocalityName" : "Neillsville",                "PostalCode" : {                   "PostalCodeNumber" : "54456"                },                "Thoroughfare" : {                   "ThoroughfareName" : "S Mound Rd"                }             },             "SubAdministrativeAreaName" : "Clark"          }       },       "CountryName" : "USA",       "CountryNameCode" : "US"    } },     "ExtendedData": {       "LatLonBox": {         "north": 44.5921279,         "south": 44.5858326,         "east": -90.5981846,         "west": -90.6802503       }     },     "Point": {       "coordinates": [ -90.6394276, 44.5889072, 0 ]     }   }, {     "id": "p2",     "address": "S Mound Rd, Neillsville, WI 54456, USA",     "AddressDetails": {    "Accuracy" : 6,    "Country" : {       "AdministrativeArea" : {          "AdministrativeAreaName" : "WI",          "SubAdministrativeArea" : {             "Locality" : {                "LocalityName" : "Neillsville",                "PostalCode" : {                   "PostalCodeNumber" : "54456"                },                "Thoroughfare" : {                   "ThoroughfareName" : "S Mound Rd"                }             },             "SubAdministrativeAreaName" : "Clark"          }       },       "CountryName" : "USA",       "CountryNameCode" : "US"    } },     "ExtendedData": {       "LatLonBox": {         "north": 44.5920678,         "south": 44.5857725,         "east": -90.6802503,         "west": -90.7004168       }     },     "Point": {       "coordinates": [ -90.6899796, 44.5889209, 0 ]     }   } ] }
    </cfsavecontent>
    <cfdump var="#deserializeJSON(myJSON1)#">
    <cfdump var="#deserializeJSON(myJSON2)#">

  • How to parse system date to return Date and in yyyy-MM-dd format?

    DateFormat dateFormat = new SimpleDateFormat ("yyyy-MM-dd");
    java.util.Date date = new java.util.Date ();
    String dateStr = dateFormat.format (date);
    try{
    Date date2 = dateFormat.parse (dateStr);
    }catch(ParseException pe){
    pe.printStackTrace();
    Actually, After parsing the date from string, again it is converted into dfault format i.e. 21 Jan 00.00.00 etc...
    But I want this parsing date in yyyy-MM-dd format and again to return date.
    Can anybody tell me how to do this?

    DateFormat dateFormat = new SimpleDateFormat
    ("yyyy-MM-dd");
    java.util.Date date = new java.util.Date ();
    String dateStr = dateFormat.format (date);
    try{
    Date date2 = dateFormat.parse (dateStr);
    }catch(ParseException pe){
    pe.printStackTrace();
    Actually, After parsing the date from string, again
    it is converted into dfault format i.e. 21 Jan
    00.00.00 etc...
    But I want this parsing date in yyyy-MM-dd format and
    again to return date.
    Can anybody tell me how to do this?A Date object does not have a format, it represents a moment in time. You can use SimpleDateFormat to return a String representing that moment in time in many formats - this does not change the Date object to have that format (which it cannot since it does not contain a format).

  • Parsing a date string

    I need to parse a bunch of date strings in 'UTCG' format (whatever that really means).
    They all look like:
    1 Jan 2001 00:00:00.00
    I can't figure out which of the Java date formats parse this. I've tried many varients of:
    DateFormat.getTimeInstance(DateFormat.MEDIUM,Locale.GERMANY)
    without success.
    Help!!!!

    Here is a bit of info from the API doc - notice in the first paragraph it talks about the Date object, format seems similar. At the bottom of info is the Short, Long, etc, format tyoes, check those out... - Bart
    public abstract class DateFormat
    extends Format
    DateFormat is an abstract class for date/time formatting subclasses which formats and parses dates or time in a language-independent manner. The date/time formatting subclass, such as SimpleDateFormat, allows for formatting (i.e., date -> text), parsing (text -> date), and normalization. The date is represented as a Date object or as the milliseconds since January 1, 1970, 00:00:00 GMT.
    DateFormat provides many class methods for obtaining default date/time formatters based on the default or a given locale and a number of formatting styles. The formatting styles include FULL, LONG, MEDIUM, and SHORT. More detail and examples of using these styles are provided in the method descriptions.
    DateFormat helps you to format and parse dates for any locale. Your code can be completely independent of the locale conventions for months, days of the week, or even the calendar format: lunar vs. solar.
    To format a date for the current Locale, use one of the static factory methods:
    myString = DateFormat.getDateInstance().format(myDate);
    If you are formatting multiple dates, it is more efficient to get the format and use it multiple times so that the system doesn't have to fetch the information about the local language and country conventions multiple times.
    DateFormat df = DateFormat.getDateInstance();
    for (int i = 0; i < a.length; ++i) {
    output.println(df.format(myDate) + "; ");
    To format a date for a different Locale, specify it in the call to getDateInstance().
    DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE);
    You can use a DateFormat to parse also.
    myDate = df.parse(myString);
    Use getDateInstance to get the normal date format for that country. There are other static factory methods available. Use getTimeInstance to get the time format for that country. Use getDateTimeInstance to get a date and time format. You can pass in different options to these factory methods to control the length of the result; from SHORT to MEDIUM to LONG to FULL. The exact result depends on the locale, but generally:
    SHORT is completely numeric, such as 12.13.52 or 3:30pm
    MEDIUM is longer, such as Jan 12, 1952
    LONG is longer, such as January 12, 1952 or 3:30:32pm
    FULL is pretty completely specified, such as Tuesday, April 12, 1952 AD or 3:30:42pm PST.

  • Parsing a date string without knowing the pattern

    Hi guys.
    Imagine this tool that works with files. At a certain point the tool reads a date from a certain file. The date may come in different flavours (read patterns), depending from file to file, I do not have control over there, so I'm stuck in this moment when I have to parse the date without knowing it's pattern. In one file it's 05-12-2005, in others it's 2007-11-03 12:50:00.
    How do I proceed here?
    Thanks.

    This is going to be a problem.
    The most obvious advice would be to create a list of known patterns and then try each of them with the String in question. One of the downsides of this is that you may get false positives, because for example you interpret a month as a day or vice-versa.
    I think your starting place will be to figure out how many different date formats you actually have. If the answer truly is more than you can count or new ones are created all the time then you are going to have address that somehow because you simply can't have that. There's just no way to deal with a unlimited number of formats.
    If you do get a list of formats then I would try what I first suggested but think of ways in which you can avoid false positives.

  • Is is possible to allow multiple date format strings pass DateFormat.parse?

    I'm trying to use DateFormat.parse to validate a date in the 20/12/08 format. I would like to allow users to input 20-12-08 or 20 12 08.
    The code currently looks like this:
    formatter = DateFormat.getDateInstance(DateFormat.SMALL, US);It is currently throwing an exception if 10-12-08 is sent in where as 10/12/08 works just fine.
    Is there a alternate us locale that is more lenient?
    setLenient(true) didn't solve the problem for me. I think that would accept 32/12/08 not 10-12-08.
    I could parse the date string and replace - or ' ' with a /.. Is that best practice?
    What other options do I have? Could I use SimpleDateFormat somehow?
    Thanks for the input

    That just doesn't seem clean. It will work, but I would rather not have a valid application flow use an exception to get its job done.
    The application is also international, so many locales on one format is valid. The US user base seems to think they can type in the date however they want. So passed into the method is the locale, I would have to modify a lot of code to send in a list of valid locales.
    The best solution for me would be to have a locale that would allow - or ' ' or /. That way I still only have to make one call to df.parse and an exception produces an invalid date message. Is that possible?
    Thanks

  • Parse Localized Date String

    The javascript function util.printd has great support for localized date strings using XFAPicture.  However, util.scand doesn't appear to have the same support.  How would I go about parsing a date string that is in a localized form?
    Thanks in advance.

    Do you have your application language preference set for Spanish for Acrobat/Reader?
    Printing is done form the Date Object and not a string value.

  • 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

  • Convert a date in String format to a Date

    Hi,
    How can I convert a date in String format to a Date object?
    I have tried:
    import java.text.*;
    import java.io.*;
    import java.util.Date;
    import java.util.Locale;
    import java.sql.*;
    public class casa {
    public static Connection con = null;
    public static Statement s = null;
    public static String sql = null;
    public static String mydate = "01.01.2001";
    /** Creates a new instance of casa */
    public casa() {
    public static void main(String[] args) throws SQLException{
    try {
    DateFormat shortFormat = DateFormat.getDateInstance(DateFormat.SHORT);
    Date date = shortFormat.parse(mydate);
    //Open Database
    con = getConnection();
    s = con.createStatement();
    sql = "select date1 from table1 where date1 <= '"+date+"'";
    ResultSet rs = s.executeQuery(sql);
    while(rs.next()){
    String aba = rs.getString("datum");
    System.out.println("New Datum = "+aba);
    } catch (Exception ex ) {
    ex.printStackTrace();
    closeConnection(s, con);
    //Connection
    private static Connection getConnection() {
    Connection con = null;
    String user ="aouzi";
    String passe ="aouzi";
    String url = "jdbc:db2:EjbTest";
    try {
    //Datenbanktreiber laden
    Class.forName("COM.ibm.db2.jdbc.app.DB2Driver");
    //Verbindung herstellen
    con = DriverManager.getConnection(url,user,passe);
    }catch(ClassNotFoundException e){
    } catch(SQLException e){}
    return con;
    //close Connection
    private static void closeConnection(Statement s, Connection con) {
    try {
    s.close();
    } catch (SQLException e) {}
    try {
    con.close();
    } catch (SQLException e) {}
    I'm getting the following errors:
    COM.ibm.db2.jdbc.DB2Exception: [IBM][CLI Driver][DB2/NT] SQL0180N
    The syntax of the representation of a date/time of day value as character sequence is false. .SQLSTATE=22007

    I'm pretty sure it won't understand what date.toString() returns. If you know what format the database understands, you do it like this:
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy"); // e.g. 18-Apr-02
    String datestring = sdf.parse(date);
    and use that instead of date in your sql string. Some databases understands it if you do
    "to_date('18-Apr-02')"
    so you could include that in your sql string as well..
    You could also try to make it a java.sql.Date and hope your jdbc driver knows how to convert it to a string that the database understands if you don't know the format:
    con = getConnection();
    PreparedStatement ps = con.prepareStatement("select date1 from table1 where date1 <= ?");
    ps.setDate(new java.sql.Date(date.getTime()));
    ResultSet rs = s.executeQuery(sql);

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

  • Can't parse XML data

    I'm receiving an XML document over a TCP socket, I then instantiate an instance of DOMParser and attempt to parse the data. Here's the exception:
    org.xml.sax.SAXParseException: An invalid XML character (Unicode: 0x0) was found in markup after the end of the element content.
         at org.apache.xerces.framework.XMLParser.reportError(XMLParser.java:1213)
         at org.apache.xerces.framework.XMLDocumentScanner.reportFatalXMLError(XMLDocumentScanner.java:588)
         at org.apache.xerces.framework.XMLDocumentScanner$TrailingMiscDispatcher.dispatch(XMLDocumentScanner.java:1461)
         at org.apache.xerces.framework.XMLDocumentScanner.parseSome(XMLDocumentScanner.java:381)
         at org.apache.xerces.framework.XMLParser.parse(XMLParser.java:1098)
    Here's the relevant snippet(s) of source (there is code to write out the socket, but I didn't include that)
    Socket socket = new Socket( hostIP, hostPort );
    OutputStream outStream = socket.getOutputStream();
    InputStream inStream = socket.getInputStream();
    DataInputStream dataInStream = new DataInputStream( inStream );
    byte[] inByteArray  = new byte[ 2048 ];
    int length =  dataInStream.read( inByteArray );
    InputStream byteData  =  new ByteArrayInputStream( inByteArray );
    try
           DOMParser dp = new DOMParser();
           dp.parse( new InputSource( byteData ));
           Document doc = dp.getDocument();
    catch ( Exception e )
            e.printStackTrace();
            System.exit( 1 );
    }Is there a different way to do this? I even tried creating a new String based on the length read from the socket, minus one. The parser then saw that the final angle bracket of my root element was missing, so it doesn't seem to be an encoding issue.
    Any help would be appreciated.
    Jeff

    An invalid XML character (Unicode: 0x0)The XML is corrupt.
    ...saw that the final angle bracket of my rootelement was missing,
    After you subtracted one from the length - that would
    suggest that not subtracting one would be a good
    idea.Yep. That was a test to verify that the data was in tact and not null terminated. To doubly check, I took an Ethereal trace of the wire, and there was no null. If I convert the byte[] to a String, everything is fine. Unfortunately,
    there wasn't a parser method that took the XML document as a String.
    >
    I would suppose that the real problem here has
    nothing to do with XML nor DOM but rather that you
    are not correctly retreiving the data from the socket.Data is fine from the socket, I just had to implement my own getAttribute() and getElementContent, and use brute force. I just thought using an already written parser made more sense.
    Thanks for the reply.

  • 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

  • Reading a file and parsing the data for a calculation method

    i am trying to read a file with 3 feilds double double and int . am able to read the file but i am getting an exception right befor i parse the data ...code
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.*;
    //import com.sun.java.util.jar.pack.Package.File;
    public class FileTester {
    public static String mLine;
         public static void main(String[] args) {
              BufferedReader in = null;
              try{
              File f = new File ("loan.txt.txt");
              in = new BufferedReader(new FileReader(f));
              catch(FileNotFoundException e)
                   System.out.println("file does not exist");
                   System.exit(0);
              try{
              String mLine = in.readLine();
              while (mLine != null){
                   System.out.println(mLine);
                   mLine = in.readLine();
              }}catch(Exception e)
              {System.out.println(e.getMessage());
              String []data = mLine.split("\t");
              double loan = Double.parseDouble(data[0]);
              double interest = Double.parseDouble(data[1]);
              int term = Integer.parseInt(data[2]);
              System.out.println(loan+interest+term);
    afterwards i would like to break this up into three methods to feed the values to a calculation class

    Take a look at your while loop. It continues to loop as long as mLine != null. Therefore it stops looping when mLine IS = null. So can you now see why the following line of code would cause problems?
    String []data = mLine.split("\t");How is the data stored in your file? Is it a single line with the three values separated by a tab? If so you can do away with the while loop and just call readLine() once. Otherwise you will have to process each line you read inside the while loop.
    P.S. use the code button when posting code. There is a button above the textfield when use post a reply.

  • Parsing Json data to Array

    i have json string which i want to parse in string and add in Array,
    also i want to access this value as per field name to display in TextBox.
    i have parse the json data in string format but i want to add it in array as per their field name,so that i can access it in textfields.
    [{"userid":1,"uname":"andruw","address":"west","city":"london","email":"[email protected]"},
    {"userid":2,"uname":"pamela","address":"east","city":"london","email":"[email protected]"},
    {"userid":3,"uname":"penny","address":"south","city":"paris","email":"[email protected]"},
    {"userid":4,"uname":"jhon","address":"north","city":"zurich","email":"[email protected]"}]

    Why do you wnat it string in hte first place, now you need to split it to get the info. The honest thing to do is to create a custom class to hold this info and populate the array with objects created from JSON. That way you can easily map data to UI controls.
    class Person
        userId:int;
        uname:String;
        address:String;
        city:String;
        email:String;
    My 2 cents,
    C

  • Parsing a date object

    I need to be able to parse out the month, day of month and the time from a date object into separate fields. I know I can use the getTime() method to retrieve the milliseconds which I believe I can work with, but I also need the month and day.

    Use the Calendar object.
    Date myDate = ....;
    Calendar cal = Calendar.getInstance();
    cal.setTime(myDate);
    int day = cal.get(Calendar.DAY);
    int month = cal.get(Calendar.MONTH);Note that the month returned by the Calendar class is ZERO based.
    ie 0 = Jan, 1 = Feb, 2=Mar.
    Of possible use to you would be the java.text.SimpleDateFormat class which converts between Dates and Strings for you.
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date d = sdf.parse("15/09/2005");Check out the API for java.util.Date, java.util.Calendar and java.text.SimpleDateFormat.
    Cheers,
    evnafets

Maybe you are looking for

  • IPhone 5 won't sync to iTunes since update to 11.1.3.8 yesterday

    I've tried repairing iTunes and resetting the sync history since I've also been getting the error message unable to load sync services. But iTunes will sync to my iPad 4. And if I make changes to my playlists on my iPhone they do update in iTunes but

  • AME CC and 2014 crashed

    Hi, I am having some difficulties transcoding from XMF to .mov (screenshot attached) at HD 1080i 25,H.264, AAC 48Khz using both the CC 7.2.2.29 and CC 2014  8.0.0.173 version with an unknown error. Would like to know if any experts can help System Sp

  • Directory log_dir full

    hello, The directory "log_dir" is full at 97%. We have in this directory redologs from January 2010. We have a backup every day successfully OS Linux Suse10 DB6 09.01.0007 My question is: How can I empty log_dir directory ?? I suppose I cannot use th

  • What is the best method for storing/retrieving images?

    Friends, OS: RHEL AS 3 DB: 9iR2 We have some critical situation. We need to scan all our Purchase orders and to store in our pc. we don't want to store the images in the database. it will be a big headache. We have 4 branches in different cities. All

  • Displaying Total Text in an ALV Grid

    Hi Experts,               Please suggest me how to display the Total text in the alv grid using CL_SALV_FACTORY method.              Example Output:              Field1            Field2         Field3              a                    b