Software Development

Developing with OpenSource and Microsoft Technologies

How to show a XML File in Java

leave a comment »

It’s very simple, we need to use a Transformer object, that can transform a source tree into a result tree. And XML Parsers to process the XML document.

package javasample_01;

import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

public class Main {

 /**
 * https://opensw.wordpress.com Mredison@2009
 */
 public static void main(String[] args) throws IOException{

 BufferedReader _bf = new BufferedReader(new InputStreamReader(System.in));
 // System.out.print("Nombre del XML: ");
 // String _archivoXML = _bf.readLine();
 String _archivoXML = "Empleados.xml";
 File _archivo = new File(_archivoXML);

 //Si el archivo existe
 if(_archivo.exists()){

 try{
 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 // Usar el factory para crear un constructor
 DocumentBuilder _constructor = factory.newDocumentBuilder();
 Document doc = _constructor.parse(_archivoXML);

 Transformer _transformer = TransformerFactory.newInstance().newTransformer();
 _transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "systmId");

 Source _recurso = new DOMSource(doc);
 Result _resultado = new StreamResult(System.out);
 _transformer.transform(_recurso, _resultado);
 System.out.println();

 }
 catch(SAXException e)
 {
 System.err.println(e.getMessage());
 }
 catch(TransformerConfigurationException e)
 {
 System.err.println(e.getMessage());
 }
 catch(ParserConfigurationException e)
 {
 System.err.println(e.getMessage());
 }
 catch(TransformerException e)
 {
 System.err.println(e.getMessage());
 }
 }

 else{
 System.out.print("Archivo No Encontrado");
 }

 }

}

javaAndXML_01

Advertisements

Written by mredison

July 27, 2009 at 6:08 am

Posted in Java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: