Código de Java - Manejo de ficheros XML

sin imagen de perfil
Val: 20
Ha disminuido 1 puesto en Java (en relación al último mes)
Gráfica de Java

Manejo de ficheros XMLgráfica de visualizaciones


Java

Publicado el 11 de Diciembre del 2018 por De (2 códigos)
1.757 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

1.0
estrellaestrellaestrellaestrellaestrella(1)

Publicado el 11 de Diciembre del 2018gráfica de visualizaciones de la versión: 1.0
1.758 visualizaciones desde el 11 de Diciembre del 2018
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
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)

Imágen de perfil
15 de Enero del 2019
estrellaestrellaestrellaestrellaestrella
Esta muy bueno tu código, ademas siempre es bueno saber el manejo de varios formatos en nuestro lenguaje favorito.
Tu código me servirá para familiarizarme en el manejo de XML desde Java.
Responder

Comentar la versión: 1.0

Nombre
Correo (no se visualiza en la web)
Valoración
Comentarios...
CerrarCerrar
CerrarCerrar
Cerrar

Tienes que ser un usuario registrado para poder insertar imágenes, archivos y/o videos.

Puedes registrarte o validarte desde aquí.

Codigo
Negrita
Subrayado
Tachado
Cursiva
Insertar enlace
Imagen externa
Emoticon
Tabular
Centrar
Titulo
Linea
Disminuir
Aumentar
Vista preliminar
sonreir
dientes
lengua
guiño
enfadado
confundido
llorar
avergonzado
sorprendido
triste
sol
estrella
jarra
camara
taza de cafe
email
beso
bombilla
amor
mal
bien
Es necesario revisar y aceptar las políticas de privacidad

http://lwp-l.com/s4964