Java - De Xml a Objeto Java

 
Vista:
Imágen de perfil de pablo
Val: 626
Bronce
Ha mantenido su posición en Java (en relación al último mes)
Gráfica de Java

De Xml a Objeto Java

Publicado por pablo (239 intervenciones) el 12/12/2023 00:12:26
Muy buenas a todos comunidad, tengo el siguiente incoveniente tengo este xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<funciones serialization="custom">
	  <unserializable-parents/>
	  <list>
	    <default>
	      <size>2</size>
	    </default>
	    <int>10</int>
	    <simm.reglas.EdadMinima>
	      <edad>18</edad>
	    </simm.reglas.EdadMinima>
	    <simm.reglas.EdadMaxima>
	      <edad>64</edad>
	    </simm.reglas.EdadMaxima>
	  </list>
	</funciones>
De dicho xml quiero extraer la edad minima y maxima más especificamente la etiqueta edad y ya he intentado con distintas librerias si solucion alguna
intente con jaxb
1
2
3
4
5
6
7
8
9
10
11
12
try {
			   JAXBContext context = JAXBContext.newInstance(Funciones.class);
 
			   Unmarshaller unmarshaller = context.createUnmarshaller();
 
			   Funciones funcion = (Funciones) unmarshaller.unmarshal(new StringReader(productoReglas));
 
			   System.out.println(funcion);
 
			}catch(Exception e) {
				System.out.println(e.getMessage());
			}
codigo de funciones
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
@XmlRootElement(name = "funciones")
@XmlAccessorType(XmlAccessType.FIELD)
public class Funciones{
 
	private static final long serialVersionUID = 1L;
 
 
	 @XmlElements(@XmlElement(name = "edad", type = EdadMinima.class))
    private List<EdadMinima> edadMinima = new ArrayList<>();
 
 
 
    private List<EdadMaxima> edadMaxima = new ArrayList<>();
 
 
	public List<EdadMinima> getEdadMinima() {
		return edadMinima;
	}
 
	public void setEdadMinima(List<EdadMinima> edadMinima) {
		this.edadMinima = edadMinima;
	}
 
	public List<EdadMaxima> getEdadMaxima() {
		return edadMaxima;
	}
 
	public void setEdadMaxima(List<EdadMaxima> edadMaxima) {
		this.edadMaxima = edadMaxima;
	}
 
 
 
	}
y las propiedades de Edadminima y maxima
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class EdadMinima extends Regla {
private final String MENSAJE_EDAD_MINIMA_NO_CUMPLIDA = "La edad '%s' introducida no cumple con la edad minima '%s' ";
 
	private final String PARAMETRO_FALTANTE = "No se encontro el parametro '%s'";
 
 
	private int edad;
 
	public int getEdad() {
		return edad;
	}
 
	public void setEdad(int edad) {
		this.edad = edad;
	}

quisiera saber si me pueden dar una mano y entender el porque no se muestran dichos valores, sin más que agregar

Saludos
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de Billy Joel
Val: 2.665
Oro
Ha mantenido su posición en Java (en relación al último mes)
Gráfica de Java

De Xml a Objeto Java

Publicado por Billy Joel (876 intervenciones) el 13/12/2023 13:48:25
Hola Pablo, acá te voy a dejar un ejemplo de como resolver.
Me gusta trabajar con la librería de JSON in Java [package org.json] cuando se trata de manejo de XML o JSON + Java.

Hice un proyecto Java de tipo Maven. El Pom quedó así:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>pablo.xml.pabloxml</groupId>
    <artifactId>PabloXML</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20231013</version>
        </dependency>
    </dependencies>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <exec.mainClass>pablo.xml.PabloXML</exec.mainClass>
    </properties>
</project>

Agregué un archivo XML con nombre funciones.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="UTF-8"?>
<funciones serialization="custom">
    <unserializable-parents/>
    <list>
        <default>
            <size>2</size>
        </default>
        <int>10</int>
        <simm.reglas.EdadMinima>
            <edad>18</edad>
        </simm.reglas.EdadMinima>
        <simm.reglas.EdadMaxima>
            <edad>64</edad>
        </simm.reglas.EdadMaxima>
    </list>
</funciones>

Ahora si vamos a la solución:
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
package pablo.xml;
 
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import org.json.JSONObject;
import org.json.XML;
 
/**
 *
 * @author Billy Joel
 */
public class PabloXML {
 
    public static final String ARCHIVO_FUNCIONES = "funciones.xml";
 
    /**
     * Lee el archivo con las funciones y retorna el contenido en un String
     *
     * @return String con el contenido de las funciones
     * @throws IOException
     */
    public static String cargarXML() throws IOException {
        String content = "";
        try ( FileReader fr = new FileReader(ARCHIVO_FUNCIONES)) {
            BufferedReader br = new BufferedReader(fr);
            String linea;
            while ((linea = br.readLine()) != null) {
                content += linea;
            }
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
        return content;
    }
 
    public static void main(String[] arg) {
 
        String funciones = null;
 
        try {
            funciones = cargarXML();
        } catch (IOException ex) {
            ex.printStackTrace(System.out);
        }
 
        if (funciones != null && !funciones.isEmpty()) {
 
            //Convierte el contenido xml a json para manejarlos como un Map
            JSONObject o = XML.toJSONObject(funciones);
 
            System.out.println("Edad maxima: " + o.getJSONObject("funciones")
                    .getJSONObject("list")
                    .getJSONObject("simm.reglas.EdadMaxima")
                    .getInt("edad"));
 
            System.out.println("Edad minima: " + o.getJSONObject("funciones")
                    .getJSONObject("list")
                    .getJSONObject("simm.reglas.EdadMinima")
                    .getInt("edad"));
        }
    }
}

El proyecto le vi potencial de ser publicado en GitHub lo puedes descargar acá
https://github.com/billyjoel01/lwp/tree/master/PabloXML

Saludos,
Billy Joel
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
1
Comentar
Imágen de perfil de pablo
Val: 626
Bronce
Ha mantenido su posición en Java (en relación al último mes)
Gráfica de Java

De Xml a Objeto Java

Publicado por pablo (239 intervenciones) el 16/12/2023 02:11:33
Buenas noches,

Muchas gracias Billy
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar