Foro de elhacker.net

Programación => Java => Mensaje iniciado por: samirllorente en 28 Marzo 2015, 07:02 am



Título: leer achivo xml en java
Publicado por: samirllorente en 28 Marzo 2015, 07:02 am
tengo el siguiente xml

Código:
<?xml version="1.0" encoding="utf-8"?>
<Gestion>
<Velocidad>100</Velocidad>
<Process>
<Pid>1</Pid>
<Name>Proceso1</Name>
<Quantum>2</Quantum>
<Actividad>
<Archivo_fuente>@"C:\Users\Samir-PC\Documents\prueba1.txt"</Archivo_fuente>
<Archivo_destino>@"C:\Users\Samir-PC\Documents"</Archivo_destino>
</Actividad>
</Process>
<Process>
<Pid>2</Pid>
<Name>Proceso2</Name>
<Quantum>1</Quantum>
<Actividad>
<Archivo_fuente>@"C:\Users\Samir-PC\Documents\prueba2.txt"</Archivo_fuente>
<Archivo_destino>@"C:\Users\Samir-PC\Documents"</>
</Actividad>
</Process>
<Process>
<Pid>3</Pid>
<Name>Proceso3</Name>
<Quantum>4</Quantum>
<Actividad>
<Archivo_fuente>@"C:\Users\Samir-PC\Documents\prueba3.txt"</Archivo_fuente>
<Archivo_destino>@"C:\Users\Samir-PC\Documents"</Archivo_destino>
</Actividad>
</Process>
<Process>
<Pid>4</Pid>
<Name>Proceso4</Name>
<Quantum>3</Quantum>
<Actividad>
<Archivo_fuente>@"C:\Users\Samir-PC\Documents\prueba4.txt"</Archivo_fuente>
<Archivo_destino>@"C:\Users\Samir-PC\Documents"</Archivo_destino>
</Actividad>
</Process>
</Gestion>

y no se como leer las etiquetas <Archivo_fuente> y  <Archivo_destino>

y lo q logre fue hacer esto 


Código:
try {
            DocumentBuilderFactory fábricaCreadorDocumento = DocumentBuilderFactory.newInstance();
            DocumentBuilder creadorDocumento = fábricaCreadorDocumento.newDocumentBuilder();
            Document documento = creadorDocumento.parse(Archivo);
            Element raiz = documento.getDocumentElement();
            NodeList listaActividad = raiz.getElementsByTagName("Process");
           
            for(int i=0; i<listaActividad.getLength(); i++){   
               
                Node Proceso= listaActividad.item(i);
                NodeList datosProcesos = Proceso.getChildNodes();
               
                Nodo nuevo=new Nodo();
                for(int j=0; j<datosProcesos.getLength(); j++) {
                   
                    Node dato = datosProcesos.item(j);
                    Node datoContenido = dato.getFirstChild();
                    if(dato.getNodeName().equals("Pid")){
                        nuevo.setPId(datoContenido.getNodeValue());
                    }
                    if(dato.getNodeName().equals("Name")){
                        nuevo.setNombre(datoContenido.getNodeValue());
                    }
                    if(dato.getNodeName().equals("Quantum")){
                        nuevo.setQuantum(Integer.parseInt(datoContenido.getNodeValue()));
                    }
                   
                }
                Listo.Agregar(nuevo);

            }
            LListo.setModel(Listo.getModelado());
        } catch (ParserConfigurationException | SAXException | IOException ex) {
            //Logger.getLogger(ClassPrincip.class.getName()).log(Level.SEVERE, null, ex);
        }

si alguien me podia con el resto se los agradeceriaa


Título: Re: leer achivo xml en java
Publicado por: Usuario Invitado en 28 Marzo 2015, 13:14 pm
Hola  samirllorente,

Puedes leer tu fichero XML mediante JAXB, que es el API de Java para manejo de ficheros XML. Lo único que necesitarás es crear clases (entidades) que representen a cada etiqueta. Un ejemplo aplicado a tu XML:

Ésta clase es el Root, es decir, la etiqueta que engloba todo (<Gestion></Gestion>):

Management

Código
  1. package com.company.model.entities;
  2.  
  3. import java.util.List;
  4. import javax.xml.bind.annotation.XmlAccessType;
  5. import javax.xml.bind.annotation.XmlAccessorType;
  6. import javax.xml.bind.annotation.XmlElement;
  7. import javax.xml.bind.annotation.XmlRootElement;
  8.  
  9. /**
  10.  *
  11.  * @author gus
  12.  */
  13. @XmlRootElement(name="Gestion")
  14. @XmlAccessorType(XmlAccessType.FIELD)
  15. public class Management {
  16.    @XmlElement(name="Velocidad")
  17.    private Double velocity;
  18.    @XmlElement(name="Process")
  19.    private List<Process> processes;
  20.  
  21.    public Management() {
  22.  
  23.    }
  24.    public Management(Double velocity, List<Process> processes) {
  25.     this.velocity = velocity;
  26.     this.processes = processes;
  27.    }
  28.    public Double getVelocity() {
  29.        return velocity;
  30.    }
  31.    public void setVelocity(Double velocity) {
  32.        this.velocity = velocity;
  33.    }
  34.    public List<Process> getProcesses() {
  35.        return processes;
  36.    }
  37.    public void setProcesses(List<Process> processes) {
  38.        this.processes = processes;
  39.    }
  40.  
  41. }

Como puedes darte cuenta hay un par de anotaciones interesantes:

  • @XmlRootElement: Indica que es el elemento padre de una jerarquía.
  • @XmlElement: Indica que es un elemento XML (un tag).
  • @XmlAccessorType, @XmlAccessType.FIELD: La primera se usa para establecer el tipo de acceso. La segunda indica que se accederá a los valores por propiedades (y no por getters/setters).

El atributo name de las anotaciones se usa para especificar el valor que deben tener las propiedades (tags) en el XML.

Ahora veamos las entidades Process y Activity:

Process

Código
  1. package com.company.model.entities;
  2.  
  3. import javax.xml.bind.annotation.XmlAccessType;
  4. import javax.xml.bind.annotation.XmlAccessorType;
  5. import javax.xml.bind.annotation.XmlElement;
  6. import javax.xml.bind.annotation.XmlRootElement;
  7.  
  8. /**
  9.  *
  10.  * @author gus
  11.  */
  12. @XmlAccessorType(XmlAccessType.FIELD)
  13. public class Process {
  14.    @XmlElement(name="Pid")
  15.    private Short pid;
  16.    @XmlElement(name="Name")
  17.    private String name;
  18.    @XmlElement(name="Quantum")
  19.    private Short quantum; // ¿quántico?
  20.    @XmlElement(name="Actividad")
  21.    private Activity activity;
  22.  
  23.    public Process() {
  24.  
  25.    }
  26.    public Process(Short pid, String name, Short quantum, Activity activity) {
  27.        this.pid = pid;
  28.        this.name = name;
  29.        this.quantum = quantum;
  30.        this.activity = activity;
  31.    }
  32.    public Short getPid() {
  33.        return pid;
  34.    }
  35.    public void setPid(Short pid) {
  36.        this.pid = pid;
  37.    }
  38.    public String getName() {
  39.        return name;
  40.    }
  41.    public void setName(String name) {
  42.        this.name = name;
  43.    }
  44.    public Short getQuantum() {
  45.        return quantum;
  46.    }
  47.    public void setQuantum(Short quantum) {
  48.        this.quantum = quantum;
  49.    }
  50.    public Activity getActivity() {
  51.        return activity;
  52.    }
  53.    public void setActivity(Activity activity) {
  54.        this.activity = activity;
  55.    }
  56.  
  57. }

Activity

Código
  1. package com.company.model.entities;
  2.  
  3. import javax.xml.bind.annotation.XmlAccessType;
  4. import javax.xml.bind.annotation.XmlAccessorType;
  5. import javax.xml.bind.annotation.XmlElement;
  6. import javax.xml.bind.annotation.XmlRootElement;
  7.  
  8. /**
  9.  *
  10.  * @author gus
  11.  */
  12. @XmlAccessorType(XmlAccessType.FIELD)
  13. public class Activity {
  14.    @XmlElement(name="Archivo_fuente")
  15.    private String source;
  16.    @XmlElement(name="Archivo_destino")
  17.    private String target;
  18.  
  19.    public Activity() {
  20.  
  21.    }
  22.    public Activity(String source, String target) {
  23.        this.source = source;
  24.        this.target = target;
  25.    }
  26.    public String getSource() {
  27.        return source;
  28.    }
  29.    public void setSource(String source) {
  30.        this.source = source;
  31.    }
  32.    public String getTarget() {
  33.        return target;
  34.    }
  35.    public void setTarget(String target) {
  36.        this.target = target;
  37.    }
  38.  
  39. }

Como puedes ver, algunas etiquetas se repiten, en concreto XmlAccessorType y es para indicar que los valores se accederán por medio de las propiedades.

NOTA: Para leer un archivo XML es importante que el atributo name de las propiedades sean idénticas al nombre del tag en el XML. De lo contrario, la conversión fallará.

Ahora, veamos quien hace "la magia". Cabe aclarar que se hace un uso mínimo de Generics para que la clase se adapte a cualquier entidad:.

MarshallerUtil

Código
  1. package com.company.model.jaxb;
  2. import java.io.File;
  3.  
  4. import javax.xml.bind.JAXBContext;
  5. import javax.xml.bind.JAXBException;
  6. import javax.xml.bind.Marshaller;
  7. import javax.xml.bind.Unmarshaller;
  8.  
  9.  
  10.  
  11. public class MarshallerUtil<T> {
  12. private static JAXBContext jaxbContext;
  13. private final Class<T> clazz;
  14.  
  15. public MarshallerUtil(Class<T> aClazz) throws JAXBException {
  16. this.clazz = aClazz;
  17. jaxbContext = JAXBContext.newInstance(clazz);
  18. }
  19.  
  20. public void marshal(T entity, File output) throws JAXBException {
  21. Marshaller marshaller = jaxbContext.createMarshaller();
  22. marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
  23. marshaller.marshal(entity, output);
  24. }
  25.  
  26. public T unmarshal(File input) throws JAXBException {
  27. Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
  28. return (T) unmarshaller.unmarshal(input);
  29. }
  30.  
  31. }

Donde:

  • T: Es el tipo de clase (entidad) que será trabajada por el Marshaller (transformador).
  • marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);: Formatea el XML.
  • marshaller.marshall(entity, file): Recibe la entidad a convertir a XML y el destino (ruta) en un objeto File.
  • marshaller.unmarshal(file): Recibe la ruta del XML a convertir. Con el cast hacia T decimos que el XML se convierta a la entidad con la que se está trabajando (T = MarshallerUtil<CLASE_DE_ENTIDAD>).

    Por último, hagamos una prueba:

    Main

Código
  1. package com.company.main;
  2.  
  3. import com.company.model.entities.Activity;
  4. import com.company.model.entities.Management;
  5. import com.company.model.entities.Process;
  6. import com.company.model.jaxb.MarshallerUtil;
  7. import com.sun.istack.internal.logging.Logger;
  8. import java.util.ArrayList;
  9. import java.util.Collections;
  10. import java.util.List;
  11. import javax.xml.bind.JAXBException;
  12.  
  13.  
  14. public class Main {
  15.  
  16. public static void main(String[] args) {
  17.            Logger logger = Logger.getLogger(Main.class);
  18.            try {
  19.                /*Management management = new Management();
  20.                 List<Process> processes = new ArrayList<>();
  21.                 Collections.addAll(processes,
  22.                         new Process(new Short("1"), "Proceso 1", new Short("1"),
  23.                             new Activity("/home/gus/Documentos/origen.txt", "home/gus/Documentos")),
  24.                         new Process(new Short("2"), "Proceso 2", new Short("4"),
  25.                             new Activity("/home/gus/Documentos/origen.xml", "home/gus/Documentos")),
  26.                         new Process(new Short("3"), "Proceso 3", new Short("3"),
  27.                             new Activity("/home/gus/Documentos/origen.sh", "home/gus/Documentos"))
  28.                 );
  29.                 management.setVelocity(100.05d);
  30.                 management.setProcesses(processes);
  31.                 MarshallerUtil<Management> marshaller = new MarshallerUtil(Management.class);
  32.                 marshaller.marshal(management, new java.io.File("/home/gus/Documentos/prueba1.xml"));*/
  33.  
  34.                MarshallerUtil<Management> marshaller = new MarshallerUtil(Management.class);
  35.                Management management = marshaller
  36.                        .unmarshal(new java.io.File("/home/gus/Documentos/prueba.xml"));
  37.                System.out.println(management.getVelocity());
  38.                for(Process process : management.getProcesses()) {
  39.                    System.out.println(process.getPid());
  40.                    System.out.println(process.getName());
  41.                    System.out.println(process.getQuantum());
  42.                    System.out.println(process.getActivity().getSource());
  43.                    System.out.println(process.getActivity().getTarget());
  44.                    System.out.println();
  45.                }
  46.            } catch (JAXBException e) {
  47.                logger.warning(e.getMessage());
  48.            }
  49.  
  50. }
  51.  
  52. }

La parte comentada es la forma para convertir una entidad a un fichero XML.

Resultado:

Citar
100.0
1
Proceso1
2
@"C:\Users\Samir-PC\Documents\prueba1.txt"
@"C:\Users\Samir-PC\Documents"

2
Proceso2
1
@"C:\Users\Samir-PC\Documents\prueba2.txt"
@"C:\Users\Samir-PC\Documents"

3
Proceso3
4
@"C:\Users\Samir-PC\Documents\prueba3.txt"
@"C:\Users\Samir-PC\Documents"

4
Proceso4
3
@"C:\Users\Samir-PC\Documents\prueba4.txt"
@"C:\Users\Samir-PC\Documents"


¡Saludos!


Título: Re: leer achivo xml en java
Publicado por: samirllorente en 29 Marzo 2015, 04:32 am
 :o gracias muchas gracias, tratare de entender esto de xml porq ni ideaa, pero lo nesecitooo


Título: Re: leer achivo xml en java
Publicado por: samirllorente en 29 Marzo 2015, 06:39 am
Me sirvio tus sugerencias, segui con el q ya tenia, pero este me sirve de todas maneras porq tengo q hacer 3 formas distintas para un trabajos :D

asi fue como hice

Código:
try {
            DocumentBuilderFactory fábricaCreadorDocumento = DocumentBuilderFactory.newInstance();
            DocumentBuilder creadorDocumento = fábricaCreadorDocumento.newDocumentBuilder();
            Document documento = creadorDocumento.parse(Archivo);
            Element raiz = documento.getDocumentElement();
           
            NodeList listaActividad = raiz.getElementsByTagName("Process");
            NodeList Velocidad = raiz.getElementsByTagName("Velocidad");
            Node NVelocidad=Velocidad.item(0);
           
            System.out.println("Velocidad: "+NVelocidad.getFirstChild().getNodeValue());
            System.out.println("");
           
            for(int i=0; i<listaActividad.getLength(); i++){   
               
                Node Proceso= listaActividad.item(i);
                NodeList datosProcesos = Proceso.getChildNodes();
               
                Nodo nuevo=new Nodo();
                for(int j=0; j<datosProcesos.getLength(); j++) {
                   
                    Node dato = datosProcesos.item(j);
                    Node datoContenido = dato.getFirstChild();
                    if(dato.getNodeName().equals("Pid")){
                        nuevo.setPId(datoContenido.getNodeValue());
                    }
                    if(dato.getNodeName().equals("Name")){
                        nuevo.setNombre(datoContenido.getNodeValue());
                    }
                    if(dato.getNodeName().equals("Quantum")){
                        nuevo.setQuantum(Integer.parseInt(datoContenido.getNodeValue()));
                    }
                    if(dato.getNodeName().equals("Actividad")){
                       
                        Node activ= datosProcesos.item(j);
                        NodeList loqsea = activ.getChildNodes();
                        for(int k=0; k<loqsea.getLength(); k++) {
                            Node dato2= loqsea.item(k);
                            Node dato3=dato2.getFirstChild();
                            if(dato2.getNodeName().equals("Archivo_fuente")){
                                nuevo.setArchivo(dato3.getNodeValue().substring(2,dato3.getNodeValue().length()-1));
                            }
                            if(dato2.getNodeName().equals("Archivo_destino")){
                                nuevo.setCarpeta(dato3.getNodeValue().substring(2,dato3.getNodeValue().length()-1));
                            }
                        }
                    }
                   
                }

                System.out.println("Pid: "+nuevo.getPId());
                System.out.println("Nombre: "+nuevo.getNombre());
                System.out.println("Quantum: "+nuevo.getQuantum());
                System.out.println("Archivo: "+nuevo.getArchivo());
                System.out.println("Carpeta: "+nuevo.getCarpeta());
                System.out.println("----------------------------------");
                Listo.Agregar(nuevo);

            }
            LListo.setModel(Listo.getModelado());
        } catch (ParserConfigurationException | SAXException | IOException ex) {
            //Logger.getLogger(ClassPrincip.class.getName()).log(Level.SEVERE, null, ex);
        }


Título: Re: leer achivo xml en java
Publicado por: Usuario Invitado en 29 Marzo 2015, 07:22 am
Por supuesto, vale perfectamente leerlo a puro código. Yo entre ambas formas, prefiero trabajar con JAXB, por un lado porque la conversión es automática y transparente para mí, y por otro lado porque siempre es bueno trabajar con entidades  :)

Saludos y gracias por compartir el código.