Manejo de ficheros XML
Java
1.847 visualizaciones desde el 11 de Diciembre del 2018
El código sirve tanto para mostrar un xml, añadir un nuevo elemento, eliminar y modificar uno
public class gestionUsuarios {
static String ruta_fichero_entrada = "files/usuarios.xml";
static String ruta_fichero_salida = "files/usuarios_copia.xml";
static Document doc = null;
public static boolean abrirXmlJDOM() throws JDOMException, IOException {
try {
SAXBuilder SAXbuilder = new SAXBuilder();
File xmlFile = new File(ruta_fichero_entrada);
doc = (Document) SAXbuilder.build(xmlFile);
return true;
} catch (IOException e) {
e.printStackTrace();
System.out.println("Error al acceder al fichero");
return false;
} catch (JDOMException eJDOM) {
eJDOM.printStackTrace();
System.out.println("error al abrir el fichero");
return false;
}
}
public static boolean guardarJDOMcomoFile() throws Exception {
try {
File xmlFile = new File(ruta_fichero_salida);
XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
xmlOutputter.output(doc, new FileOutputStream(xmlFile));
} catch (Exception e) {
e.printStackTrace();
System.out.println("error al guardar el fichero");
return false;
}
return true;
}
public static String recorrerJDOMyMostrar() throws Exception {
String texto_salida = "";
try {
Element rootNode = doc.getRootElement();
List<Element> list = rootNode.getChildren("usuario");
for (int i = 0; i < list.size(); i++) {
Element temp = (Element) list.get(i);
texto_salida += "Nombre: " + temp.getChildText("nombre") + "\n";
texto_salida += "Apellidos: " + temp.getChildText("apellido") + "\n";
texto_salida += "Dirección: " + temp.getChildText("direccion") + "\n";
texto_salida += "Ciudad: " + temp.getChildText("ciudad") + "\n";
Element ciudad = temp.getChild("ciudad");
//texto_salida += "País: " + ciudad.getAttribute("pais").getValue() + "\n";
texto_salida += "País: " + ciudad.getAttributeValue("pais") + "\n";
Element contacto = temp.getChild("contacto");
texto_salida += "Teléfono: " + contacto.getChildText("telefono") + "\n";
texto_salida += "Url: " + contacto.getChildText("url") + "\n";
texto_salida += "E-Mail: " + contacto.getChildText("email") + "\n";
texto_salida += "------------------------------" + "\n";
}
}catch(Exception e) {
e.printStackTrace();
System.out.println("error al leer el fichero xml");
}
return texto_salida;
}
public static boolean annadirJDOM(String nombre, String apellido, String direccion, String ciudad, String pais, String telefono, String url, String email) throws Exception {
try {
Element rootNode = doc.getRootElement();
Element newUsuario = new Element("usuario");
Element newNombre = new Element("nombre");
newNombre.setText(nombre);
Element newApellido = new Element("apellido");
newApellido.setText(apellido);
Element newDireccion = new Element("direccion");
newDireccion.setText(direccion);
Element newCiudad = new Element("ciudad");
newCiudad.setText(ciudad);
newCiudad.setAttribute("pais", pais);
Element newContacto = new Element("contacto");
Element newTelefono = new Element("telefono");
newTelefono.setText(telefono);
Element newUrl = new Element("url");
newUrl.setText(url);
Element newEmail = new Element("email");
newEmail.setText(email);
// Contacto
newContacto.addContent(newTelefono);
newContacto.addContent(newUrl);
newContacto.addContent(newEmail);
// Usuario
newUsuario.addContent(newNombre);
newUsuario.addContent(newApellido);
newUsuario.addContent(newDireccion);
newUsuario.addContent(newCiudad);
newUsuario.addContent(newContacto);
rootNode.addContent(newUsuario);
}catch(Exception e) {
e.printStackTrace();
System.out.println("error al insertar un nuevo elemento");
return false;
}
return true;
}
public static boolean modificarJDOM(String nombre, String apellido, String telefono_nuevo) throws Exception {
try {
String nombre_xml = "";
String apellido_xml = "";
Element rootNode = doc.getRootElement();
List<Element> list = rootNode.getChildren("usuario");
for (int i = 0; i < list.size(); i++) {
Element temp = (Element) list.get(i);
Element contacto = temp.getChild("contacto");
nombre_xml = temp.getChildText("nombre");
apellido_xml = temp.getChildText("apellido");
if (nombre.equals(nombre_xml) && apellido.equals(apellido_xml)) {
contacto.getChild("telefono").setText(telefono_nuevo);
}
}
}catch(Exception e) {
e.printStackTrace();
System.out.println("error al modificar el elemento");
return false;
}
return true;
}
public static boolean modificarJDOM1(String telefono_antiguo, String telefono_nuevo) throws Exception {
try {
String telefono = "";
Element rootNode = doc.getRootElement();
List<Element> list = rootNode.getChildren("usuario");
for (int i = 0; i < list.size(); i++) {
Element temp = (Element) list.get(i);
Element contacto = temp.getChild("contacto");
telefono = contacto.getChildText("telefono");
if (telefono_antiguo.equals(telefono)) {
contacto.getChild("telefono").setText(telefono_nuevo);
}
}
}catch(Exception e) {
e.printStackTrace();
System.out.println("error al modificar el elemento");
return false;
}
return true;
}
public static boolean eliminarJDOM(String nombre, String apellido) throws Exception {
try {
String nombre_original = "";
String apellido_original = "";
Element rootNode = doc.getRootElement();
List<Element> list = rootNode.getChildren("usuario");
for (int i = 0; i < list.size(); i++) {
Element temp = (Element) list.get(i);
nombre_original = temp.getChildText("nombre");
apellido_original = temp.getChildText("apellido");
if (nombre_original.equals(nombre) && apellido_original.equals(apellido)) {
rootNode.removeContent(temp);
}
}
}catch(Exception e) {
e.printStackTrace();
System.out.println("error al eliminar el libro");
return false;
}
return true;
}
public static void main(String[] args) {
try {
if (abrirXmlJDOM()){
if(doc != null){
String salida = recorrerJDOMyMostrar();
System.out.println("-- FICHERO ORIGINAL --" + "\n");
System.out.println(salida);
doc = null;
if (abrirXmlJDOM()){
if(doc != null){
salida = recorrerJDOMyMostrar();
System.out.println("-- FICHERO FINAL --" + "\n");
System.out.println(salida);
if(annadirJDOM("Jose Luis", "Rodríguez Sevilla", "Calle Principal, 1", "Madridejos", "España", "+34 666 6666 6666", "http://www.joseluisrodriguez.es", "jlrodriguez@efamoratalaz.com")) {
guardarJDOMcomoFile(); // Hacer efectivo el cambio en el fichero XML
salida = recorrerJDOMyMostrar();
System.out.println("-- DOC DESPUÉS DE INSERTAR --" + "\n");
System.out.println(salida);
}
if(modificarJDOM("Jose Luis", "Rodríguez Sevilla", "+34 611 611 611")) {
guardarJDOMcomoFile(); // Hacer efectivo el cambio en el fichero XML
salida = recorrerJDOMyMostrar();
System.out.println("-- DOC DESPUÉS DE MODIFICAR --" + "\n");
System.out.println(salida);
}
if(eliminarJDOM("Monnie", "Boddie")) {
guardarJDOMcomoFile(); // Hacer efectivo el cambio en el fichero XML
salida = recorrerJDOMyMostrar();
System.out.println("-- DOC DESPUÉS DE ELIMINAR --" + "\n");
System.out.println(salida);
}
}
}
// Mostrar el contenido del fichero de salida .xml
ruta_fichero_entrada = ruta_fichero_salida;
doc = null;
if (abrirXmlJDOM()){
if(doc != null){
salida = recorrerJDOMyMostrar();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Comentarios sobre la versión: 1.0 (1)
Tu código me servirá para familiarizarme en el manejo de XML desde Java.