views:

246

answers:

2

Hi,

I have student.xml file and am parsing this file using SAX Parser and now I need to store data into MySQL Database and so what approach is recommended.

Code:

package sax;

    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;

    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;

    public class ReadXML extends DefaultHandler{

        public void characters(char[] ch, int start, int length) throws SAXException {
         String s =new String(ch, start, length);
         if(s.trim().length()>0) {
          System.out.println(" Value: "+s);
         }
        }

        public void startDocument() throws SAXException {
         System.out.println("Start document");
        }

        public void endDocument() throws SAXException {
         System.out.println("End document");
        }

        public void startElement(String uri, String localName, String name,
          Attributes attributes) throws SAXException {
         System.out.println("start element : "+name);

        }

        public void endElement(String uri, String localName, String name) throws SAXException {
         System.out.println("end element");
        }

        public static void main(String[] args) {
         ReadXML handler = new ReadXML();

            try { 
             SAXParserFactory factory = SAXParserFactory.newInstance();

          SAXParser saxParser = factory.newSAXParser();

             saxParser.parse("student.xml", handler); 
            } catch (Exception e) {
             e.printStackTrace();
            }
        }

    }
+1  A: 

I would create a set of tables that represent the data contained in students.xml and then populate them as you parse the data.

Brian Fisher
A: 

You might be able to directly store the XML into the DB. Many DB packages have the functionality that allows for XML formated data to be inserted into the appropriate spots in the database. I believe that PostGres and MS-SQL can do it.

There is existing functionality to do this in MySQL. See here

monksy