Foros del Web » Programación para mayores de 30 ;) » Java »

Extraer datos de un xml

Estas en el tema de Extraer datos de un xml en el foro de Java en Foros del Web. Hola. Necesito extraer los datos de un archivo XML desde java, no se si con alguna libreria o algo por el estilo, gracias...
  #1 (permalink)  
Antiguo 18/02/2008, 16:25
 
Fecha de Ingreso: noviembre-2007
Mensajes: 12
Antigüedad: 16 años, 5 meses
Puntos: 0
Extraer datos de un xml

Hola.
Necesito extraer los datos de un archivo XML desde java, no se si con alguna libreria o algo por el estilo, gracias
  #2 (permalink)  
Antiguo 19/02/2008, 13:15
Avatar de gustavoh10  
Fecha de Ingreso: diciembre-2005
Ubicación: ARGENTINA
Mensajes: 196
Antigüedad: 18 años, 4 meses
Puntos: 3
Re: Extraer datos de un xml

Los proyectos que se que existen para parsear un xml son:

SAX
JDOM
JAXP

Hace mucho había usado SAX, pero no me acuerdo.
Creo que JDom es mas fácil y entendible que las otras..

Saludos!
  #3 (permalink)  
Antiguo 20/02/2008, 13:18
Avatar de djagu_26  
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 518
Antigüedad: 16 años, 3 meses
Puntos: 6
Re: Extraer datos de un xml

hola mira yo uso las librerias de xerces para parsear un xml es muy sencillo aca te dejo un fragmento de codigo que lo unico que tienes q hacer es pasarle un archivo xml como parametros y el se encarga de leerlo, tambien esta el metodo para guardar un archivo xml.

import Dominio.CargoEmpleado;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.apache.xerces.jaxp.DocumentBuilderFactoryImpl;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.xml.sax.SAXException;

/**
*
* @author djagus
*/
public class ExportarCargoyEmpleadosXML {

// Etiquetas XML Cargo
private static final String TAG_PERSONAL = "Personal";
private static final String TAG_CARGOS = "Cargos";
private static final String TAG_CARGO = "Cargo";
private static final String TAG_ID_CARGO = "IDCargo";
private static final String TAG_NOMBRE_CARGO = "NombreCargo";
private static final String TAG_PORCENTAJE_CARGO = "Porcentaje";
//Codificación Estandar
private static final String XML_VERSION = "1.0";
private static final String XML_ENCODING = "ISO-8859-1";
private static final String JAVA_ENCODING = "8859_1";
// Definición de Nombre de Archivo a Grabar
private String NOMBRE_ARCHIVO_XML;
// Variables
private Document xmlDoc = null;
private Element cargos = null;
private Element personal2 = null;
private Document dom;
private ArrayList<CargoEmpleado> cargosEmpleados = new ArrayList<CargoEmpleado>();

/** Creates a new instance of ExportarCargoyEmpleadosXML */
public ExportarCargoyEmpleadosXML(String ruta) {
this.NOMBRE_ARCHIVO_XML = ruta;
}

public ExportarCargoyEmpleadosXML(File archivo) {
parseXmlFile(archivo);
}

public void generaDocumentoXML() {
try {
// Crea un documento XML
DocumentBuilderFactory dbFactory = DocumentBuilderFactoryImpl.newInstance();
DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
xmlDoc = docBuilder.newDocument();
} catch (Exception e) {
System.out.println("Error : " + e);
}

// crea un elemento personal
personal2 = xmlDoc.createElement(TAG_PERSONAL);
cargos = xmlDoc.createElement(TAG_CARGOS);
xmlDoc.appendChild(personal2);
xmlDoc.getDocumentElement().appendChild(cargos);
xmlDoc.getDocumentElement().appendChild(personal);
}

public void generaDocumentoXMLCargo(CargoEmpleado cargo) {
Element elementoCargo;
Element item;

// crea los tags de cargo
elementoCargo = xmlDoc.createElement(TAG_CARGO);
elementoCargo.setAttribute(TAG_ID_CARGO, String.valueOf(cargo.getId()));
cargos.appendChild(elementoCargo);

item = xmlDoc.createElement(TAG_NOMBRE_CARGO);
item.appendChild(xmlDoc.createTextNode(cargo.getNo mbre()));
elementoCargo.appendChild(item);

item = xmlDoc.createElement(TAG_PORCENTAJE_CARGO);
item.appendChild(xmlDoc.createTextNode(String.valu eOf(cargo.getPorcentaje())));
elementoCargo.appendChild(item);
}

// genera el objeto de documento XML en una cadena de texto
public String generaTextoXML() {

StringWriter strWriter = null;
XMLSerializer xmlSerializer = null;
OutputFormat outFormat = null;

try {
xmlSerializer = new XMLSerializer();
strWriter = new StringWriter();
outFormat = new OutputFormat();

// estableciendo el formato
outFormat.setEncoding(XML_ENCODING);
outFormat.setVersion(XML_VERSION);
outFormat.setIndenting(true);
outFormat.setIndent(4);

// Define una escritura
xmlSerializer.setOutputCharStream(strWriter);

// Aplicando el formato establecido
xmlSerializer.setOutputFormat(outFormat);

// Serializando el documento XML
xmlSerializer.serialize(xmlDoc);
strWriter.close();
} catch (IOException ioEx) {
System.out.println("Error : " + ioEx);
}
return strWriter.toString();
}

public void grabaDocumentoXML(String textoXML) {
try {
OutputStream fout = new FileOutputStream(NOMBRE_ARCHIVO_XML + ".xml");
OutputStream bout = new BufferedOutputStream(fout);
OutputStreamWriter out = new OutputStreamWriter(bout, JAVA_ENCODING);
out.write(textoXML);
out.flush();
out.close();
} catch (UnsupportedEncodingException e) {
System.out.println("La Máquina Virtual no soporta la codificación Latin-1.");
} catch (IOException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println("Error : " + e);
}
}

public void parseXmlFile(File archivo) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
//parse using builder to get DOM representation of the XML file
dom = db.parse(archivo);
parseDocumentCargos();
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (SAXException se) {
se.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}

public void parseDocumentCargos() {
Element docEle = dom.getDocumentElement();
NodeList nl = docEle.getElementsByTagName(TAG_CARGO);
if (nl != null && nl.getLength() > 0) {
for (int i = 0; i < nl.getLength(); i++) {
Element el = (Element) nl.item(i);
CargoEmpleado c = getCargo(el);
getCargosEmpleados().add(c);
}
}
}

public CargoEmpleado getCargo(Element caEl) {
CargoEmpleado c = new CargoEmpleado();
c.setId(Integer.parseInt(caEl.getAttribute(TAG_ID_ CARGO)));
c.setNombre(getTextValue(caEl, TAG_NOMBRE_CARGO));
c.setPorcentaje(Double.parseDouble(getTextValue(ca El, TAG_PORCENTAJE_CARGO)));
return c;
}

public String getTextValue(Element ele, String tagName) {
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if (nl != null && nl.getLength() > 0) {
Element el = (Element) nl.item(0);
textVal = el.getFirstChild().getNodeValue();
}
return textVal;
}

public ArrayList<CargoEmpleado> getCargosEmpleados() {
return cargosEmpleados;
}

public void setCargosEmpleados(ArrayList<CargoEmpleado> cargosEmpleados) {
this.cargosEmpleados = cargosEmpleados;
}

}

/////////////////////////Clase cargo Empleado//////////////////////
/**
*
* @author djagus
*/

/**
*Esta clase nos determina los datos de los tipos de cargos de empleado que podra tener un empleado.
*/
public class CargoEmpleado {

private int id;
private String nombre;
private double porcentaje;
private boolean borrado;

/** Creates a new instance of CargoEmpleado */
public CargoEmpleado() {
}
/**
*@return Integer
*/
public int getId() {
return id;
}
/**
*@param id Integer
*/
public void setId(int id) {
this.id = id;
}
/**
*@return String
*/
public String getNombre() {
return nombre;
}
/**
*@param nombre String
*/
public void setNombre(String nombre) {
this.nombre = nombre;
}
/**
*@return Double
*/
public double getPorcentaje() {
return porcentaje;
}
/**
*@param porcentaje Double
*/
public void setPorcentaje(double porcentaje) {
this.porcentaje = porcentaje;
}
}

espero haberte ayudado por las dudas las librerias de xerces te las puedes bajar de aqui http://xerces.apache.org/
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 22:21.