Click here to Skip to main content
15,885,915 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to insert to following parser the ability to save parsed data.
Do i need to write to the new file every parsed line ,or i can save all the processed data directly into file from main() method ?

P.s. Im a new to Java language and any support will be appreciated.
Thx in advance.

TrivialSAXHandler
Java
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

class TrivialSAXHandler extends DefaultHandler {
    
        public void newFile(){
            try {
                PrintWriter writer = new PrintWriter("nouveauDemo.xml");
            } catch (FileNotFoundException ex) {
                Logger.getLogger(TrivialSAXHandler.class.getName()).log(Level.SEVERE, null, ex);
                System.err.println("File not found");
            }

}
	public void setDocumentLocator(Locator locator) {   
                                       System.out.println("Location : " +
                                                 "publicId=" + locator.getPublicId() +
                                                 "systemId=" + locator.getSystemId());
	}
	public void startDocument(){            
		System.out.println("Debut RSS");
	}
	public void endDocument(){           
		System.out.println("Fin RSS");
                
	}
	public void startElement(String namespace,String qualname,Attributes atts) {
            
		 System.out.println("Debut de balise : " +
                                    "namespace=" +namespace +
                                    "qualname="  +qualname);
		 System.out.println("NB atttibuts : " +
				     atts.getLength());
		for (int i=0;i<atts.getLength();i++) System.out.println("NB atttibuts : " +i+ " name "+atts.getQName(i)+"  = "+atts.getValue(i));
	}
	public void endElement(String namespace,String qualname) {
		System.out.println("Balise fermante : " + 
				   "namespace="+namespace+
				   "qualname="+qualname);
                
	}
	public void characters(char[] ch, int start, int length) {
		System.out.print("Info: ");
		for(int i = start; i < start+length; i++)
			System.out.print(ch[i]);
		
	}

	public void error(SAXParseException e) {
		System.err.println("Erreur non fatale (ligne " +
				e.getLineNumber() + ", col " +
				e.getColumnNumber() + ") : " + e.getMessage());
	}
	public void fatalError(SAXParseException e) {
		System.err.println("Erreur fatale : " + e.getMessage());
	}
	public void warning(SAXParseException e) {
		System.err.println("warning : " + e.getMessage());
	}
}


TrivialSAXRead (main)
Java
import java.io.InputStream;
import java.io.FileInputStream;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;

class TrivialSAXRead {
	public static void main(String [] args)

			throws Exception
			{
		System.out.println("Demarrage SAX");

		SAXParserFactory parserFactory = SAXParserFactory.newInstance();

		SAXParser parser = parserFactory.newSAXParser();

		for(int i = 0; i < args.length; i++) {

			InputStream is = new FileInputStream(args[i]);
			parser.parse(is, new TrivialSAXHandler());
		}
			}
}
Posted
Updated 27-Nov-14 5:13am
v3

1 solution

You need to 1) open the file, 2) parse XML; 3) close the file. In your SAX handler, replace you System.out.println(...) with the statement writing to the file.

Let's consider writing to the file separately, parsing separately, and the put it all together.

First, let's assume you want to write some parsed data to a text file. For writing, let's use the class java.io.PrintWriter:
https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html[^].

So, writing to the file looks like
Java
PrintWriter writer = new PrintWriter(outputFileName, encoding); // look at documentation for the detail

// ...

writer.println("some text");

// ...

writer.close();

This scenario looks very similar if you write in binary form; then you can use the class java.io.FileOutputStream:
https://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html[^].

To put it all together, you have to pass the reference to the writer to each of your handler methods where you write something. How? you don't have parameters for this purpose. Through implicit "this" parameter, which is a reference to the instance. Therefore, you need to have a reference to the writer as a member of the SAX handling class, an instance field.

The simplest scenario looks like this: add a class constructor to accept either the writer (or binary stream) reference, or the file name (then you create a writer instance or binary stream from the name in that constructor). Assign the obtained writer/stream reference to your field. In each of the SAX handler methods, use this reference for writing. At the end of parsing, close the file. If your constructor created the writer/stream object, close it in the destructor. If you passed already created writer/stream from external code, close the file in external code after parsing.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900