Example usage for org.jdom2.input SAXBuilder build

List of usage examples for org.jdom2.input SAXBuilder build

Introduction

In this page you can find the example usage for org.jdom2.input SAXBuilder build.

Prototype

@Override
public Document build(final String systemId) throws JDOMException, IOException 

Source Link

Document

This builds a document from the supplied URI.

Usage

From source file:middleware.Reserva.java

public static ArrayList<Reserva> ConsultarReservas() {
    //lista de reservaas
    ArrayList<Reserva> listaReservas = new ArrayList<Reserva>();

    //Se crea un SAXBuilder para poder parsear el archivo
    SAXBuilder builder = new SAXBuilder();
    //archivo que tiene las reservas
    File xmlFile = new File("reserva.xml");
    try {/*from   w  w w.  ja  v a2 s  .co m*/
        //Se crea el documento a traves del archivo
        Document document = (Document) builder.build(xmlFile);
        //Se obtiene la raiz 'reservas'
        Element rootNode = document.getRootElement();
        //Se obtiene la lista de hijos de la raiz 'vuelo'
        List list = rootNode.getChildren("reserva");
        //Se recorre la lista de hijos de 'disponibilidad'
        for (int i = 0; i < list.size(); i++) {//objeto de reservas
            Reserva objeto = new Reserva();
            //Se obtiene el elemento 'vuelo'
            Element tabla = (Element) list.get(i);

            //Se obtiene el atributo 'id' que esta en el tag 'vuelo'
            String idVuelo = tabla.getAttributeValue("clave");
            objeto.setReserva(idVuelo);

            //Se obtiene la lista de hijos del tag 'reserva'   
            List lista_campos = tabla.getChildren();
            //Se obtiene la lista de hijos del tag 'vuelo'  
            Element tabla2 = (Element) lista_campos.get(0);
            List Lista_nombres = tabla2.getChildren();
            //Se recorre la lista de campos
            for (int j = 0; j < lista_campos.size(); j++) {
                //Se obtiene el elemento 'campo'
                Element campo = (Element) lista_campos.get(j);
                Element hijosCampo = (Element) Lista_nombres.get(j);
                //Se obtienen los valores que estan entre los tags 
                //se guarda en el objeto los datos de la reserva
                String linea = campo.getAttributeValue("clave");
                String lineaNombre = hijosCampo.getTextTrim();
                if (campo.getName() == "vuelo") {
                    //linea= campo.getAttributeValue("vuelo");
                    objeto.setVuelo(linea);
                }
                if (hijosCampo.getName() == "nombre") {

                    objeto.setNombre(lineaNombre);
                }
                //System.out.println( "\t"+linea+"\t\t");
                //listaVuelos.add(i,objeto);
            }
            //se agrega a la lista el objeto
            listaReservas.add(objeto);
            //System.out.println( "\"\t\t");
        }
        //listaVuelos. add(objeto);
    } catch (IOException io) {
        System.out.println(io.getMessage());
    } catch (JDOMException jdomex) {
        System.out.println(jdomex.getMessage());
    } // se retorna la lista de las reservas
    return listaReservas;

}

From source file:middleware.Reserva.java

public static void ReservarVuelo(String nombre, String vueloReserva) {
    int numeroReservas = 0;
    int id = 0;/*from w w w  . j  a  v a 2s.co m*/
    try {
        //Se crea un SAXBuilder para poder parsear el archivo
        SAXBuilder builder = new SAXBuilder();
        //archivo que tiene las reservas
        File xmlFile = new File("reserva.xml");
        //Se crea el documento a traves del archivo
        Document doc = (Document) builder.build(xmlFile);
        //se obtiene el padre del xml
        Element rootNode = doc.getRootElement();
        XMLOutputter xmlOutput = new XMLOutputter();
        Element reserva = new Element("reserva");
        //se crea una lista de losh hijos reserva
        List list = rootNode.getChildren("reserva");
        //tamao de la lista de reservas
        numeroReservas = list.size();
        //aqui se gerar el id automatico que sera la cantidad de nodos hijos mas 1
        id = numeroReservas + 1;
        //se crea el nodo reserva con id         
        reserva.setAttribute(new Attribute("clave", Integer.toString(id)));
        Element vuelo = new Element("vuelo");
        //se crean los hijos de reserva que son vuelo y nombre
        vuelo.setAttribute(new Attribute("clave", vueloReserva));
        //se agregan el nodo hijo nombre en el nodo reserva 
        vuelo.addContent(new Element("nombre").setText(nombre));
        //se inserta el nodo vuelo en el nodo reserva
        reserva.addContent(vuelo);
        //se agrega el nodo reserva al nodo padre del xml
        doc.getRootElement().addContent(reserva);
        // display nice nice
        xmlOutput.setFormat(Format.getPrettyFormat());
        //se guardan los cambios en el xml
        xmlOutput.output(doc, new FileWriter("reserva.xml"));

        System.out.println("Reserva agregada con id: " + id);

    } catch (IOException io) {
        io.printStackTrace();
    } catch (JDOMException e) {
        e.printStackTrace();
    }

}

From source file:middleware.Vuelo.java

public static void EditarCapacidadVuelo(String vuelo) {
    //se crea una lista de vuelos
    ArrayList<Vuelo> listaVuelos = new ArrayList<Vuelo>();
    //se llena la lista co todos los vuelos
    listaVuelos = ConsultarVuelos();/* w  w  w  . ja va2s  . c o  m*/
    //se crea un objeto vuelo para poder acceder manipular las funciones get y set
    Vuelo objetoVuelo = new Vuelo();
    int capacidadVuelo = 0;
    try {
        //Se crea un SAXBuilder para poder parsear el archivo
        SAXBuilder builder = new SAXBuilder();
        //archivo que tiene las reservas
        File xmlFile = new File("disponibilidad.xml");
        //objeto que caragra el archivo tipo document
        Document doc = (Document) builder.build(xmlFile);
        //se obtiene el padre del xml
        Element rootNode = doc.getRootElement();
        //se obtiene el hijo "vuelo"
        List reservas = rootNode.getChildren("vuelo");
        //se declara un iterator para recorrer el archivo
        Iterator iter = reservas.iterator();
        //se recorre el archivo
        while (iter.hasNext()) {
            Element reserva = (Element) iter.next();
            //se elimina el vuelo que se editara 
            if (reserva.getAttributeValue("id").equals(vuelo)) {
                iter.remove();
            }
        }

        XMLOutputter xmlOutput = new XMLOutputter();
        // display nice nice
        xmlOutput.setFormat(Format.getPrettyFormat());
        //se guardan los cambios
        xmlOutput.output(doc, new FileWriter("disponibilidad.xml"));

    } catch (IOException io) {
        io.printStackTrace();
    } catch (JDOMException e) {
        e.printStackTrace();
    }
    //se recorre la lista de vuelos del xml
    for (int i = 0; i < listaVuelos.size(); i++) {
        // si vuelo en la lista donde esta parado el for es igual al vuelo que queremos editar de llena el objeto
        if (listaVuelos.get(i).getId().equals(vuelo)) {
            capacidadVuelo = Integer.parseInt(listaVuelos.get(i).getCapacidad());
            capacidadVuelo = capacidadVuelo - 1;
            objetoVuelo.setId(listaVuelos.get(i).getId());
            objetoVuelo.setLinea(listaVuelos.get(i).getLinea());
            objetoVuelo.setOrigen(listaVuelos.get(i).getOrigen());
            objetoVuelo.setDestino(listaVuelos.get(i).getDestino());
            objetoVuelo.setFecha(listaVuelos.get(i).getFecha());
            objetoVuelo.setHora(listaVuelos.get(i).getHora());
            objetoVuelo.setCapacidad(Integer.toString(capacidadVuelo));
            objetoVuelo.setPrecio(listaVuelos.get(i).getPrecio());
        }
    }
    // se llama a la funcion editar vuelo que insertara el vuelo de nuevo en el xml pero con la capacidad nueva
    EditarVuelo(objetoVuelo.getId(), objetoVuelo.getLinea(), objetoVuelo.getOrigen(), objetoVuelo.getDestino(),
            objetoVuelo.getFecha(), objetoVuelo.getHora(), objetoVuelo.getCapacidad(), objetoVuelo.getPrecio());

}

From source file:middleware.Vuelo.java

public static void EditarVuelo(String id, String linea, String origen, String destino, String fecha,
        String hora, String capacidad, String precio) {
    int numeroVuelos = 0;

    try {//from   ww  w .  j  a va  2s.c  om
        //Se crea un SAXBuilder para poder parsear el archivo
        SAXBuilder builder = new SAXBuilder();
        //archivo con los vuelos
        File xmlFile = new File("disponibilidad.xml");
        ////objeto que caragra el archivo tipo document
        Document doc = (Document) builder.build(xmlFile);
        //nodo raiz del xml
        Element rootNode = doc.getRootElement();
        XMLOutputter xmlOutput = new XMLOutputter();
        //se crea nodo vuelo
        Element vuelo = new Element("vuelo");
        //se crea lista de vuelos
        List list = rootNode.getChildren("vuelo");
        //se guarda el tamao de la lista
        numeroVuelos = list.size();
        //id autogenerado de los vuelos

        //se crea el nodo de vuelos          
        vuelo.setAttribute(new Attribute("id", (id)));
        vuelo.addContent(new Element("linea").setText(linea));
        vuelo.addContent(new Element("origen").setText(origen));
        vuelo.addContent(new Element("destino").setText(destino));
        vuelo.addContent(new Element("fecha").setText(fecha));
        vuelo.addContent(new Element("hora").setText(hora));
        vuelo.addContent(new Element("capacidad").setText(capacidad));
        vuelo.addContent(new Element("precio").setText(precio));
        //se agrega el nodo vuelo al noda raiz
        doc.getRootElement().addContent(vuelo);
        // display nice nice
        xmlOutput.setFormat(Format.getPrettyFormat());
        //guarda cambios en el xml
        xmlOutput.output(doc, new FileWriter("disponibilidad.xml"));

        System.out.println("Vuelo agregado!");

    } catch (IOException io) {
        io.printStackTrace();
    } catch (JDOMException e) {
        e.printStackTrace();
    }

}

From source file:middleware.Vuelo.java

public static void CargarVuelo(String linea, String origen, String destino, String fecha, String hora,
        String capacidad, String precio) {
    int numeroVuelos = 0;
    int id = 0;/* ww w  .j  a v  a  2 s  .  c  o  m*/
    try {
        //Se crea un SAXBuilder para poder parsear el archivo
        SAXBuilder builder = new SAXBuilder();
        //archivo con los vuelos
        File xmlFile = new File("disponibilidad.xml");
        ////objeto que caragra el archivo tipo document
        Document doc = (Document) builder.build(xmlFile);
        //nodo raiz del xml
        Element rootNode = doc.getRootElement();
        XMLOutputter xmlOutput = new XMLOutputter();
        //se crea nodo vuelo
        Element vuelo = new Element("vuelo");
        //se crea lista de vuelos
        List list = rootNode.getChildren("vuelo");
        //se guarda el tamao de la lista
        numeroVuelos = list.size();
        //id autogenerado de los vuelos
        id = numeroVuelos + 1;
        //se crea el nodo de vuelos          
        vuelo.setAttribute(new Attribute("id", Integer.toString(id)));
        vuelo.addContent(new Element("linea").setText(linea));
        vuelo.addContent(new Element("origen").setText(origen));
        vuelo.addContent(new Element("destino").setText(destino));
        vuelo.addContent(new Element("fecha").setText(fecha));
        vuelo.addContent(new Element("hora").setText(hora));
        vuelo.addContent(new Element("capacidad").setText(capacidad));
        vuelo.addContent(new Element("precio").setText(precio));
        //se agrega el nodo vuelo al noda raiz
        doc.getRootElement().addContent(vuelo);
        // display nice nice
        xmlOutput.setFormat(Format.getPrettyFormat());
        //guarda cambios en el xml
        xmlOutput.output(doc, new FileWriter("disponibilidad.xml"));

        System.out.println("Vuelo agregado con: " + id);

    } catch (IOException io) {
        io.printStackTrace();
    } catch (JDOMException e) {
        e.printStackTrace();
    }

}

From source file:middleware.Vuelo.java

public static ArrayList<Vuelo> ConsultarVuelos() {

    ArrayList<Vuelo> listaVuelos = new ArrayList<Vuelo>();

    //Se crea un SAXBuilder para poder parsear el archivo
    SAXBuilder builder = new SAXBuilder();
    File xmlFile = new File("disponibilidad.xml");
    try {/*w  ww  .j a va  2 s  .com*/
        //Se crea el documento a traves del archivo
        Document document = (Document) builder.build(xmlFile);
        //Se obtiene la raiz 'disponibilidad'
        Element rootNode = document.getRootElement();
        //Se obtiene la lista de hijos de la raiz 'vuelo'
        List list = rootNode.getChildren("vuelo");
        //Se recorre la lista de hijos de 'disponibilidad'
        for (int i = 0; i < list.size(); i++) {
            Vuelo objeto = new Vuelo();
            //Se obtiene el elemento 'vuelo'
            Element tabla = (Element) list.get(i);
            //Se obtiene el atributo 'id' que esta en el tag 'vuelo'
            String idVuelo = tabla.getAttributeValue("id");
            objeto.setId(idVuelo);
            //Se obtiene la lista de hijos del tag 'vuelo'   
            List lista_campos = tabla.getChildren();
            //Se recorre la lista de campos
            for (int j = 0; j < lista_campos.size(); j++) {
                //Se obtiene el elemento 'campo'
                Element campo = (Element) lista_campos.get(j);
                //Se obtienen los valores que estan entre los tags '<campo></campo>'
                //Se obtiene el valor que esta entre los tags '<nombre></nombre>'
                String linea = campo.getTextTrim();
                //dependiendo de la etiqueta que esta parada guarda en un atributo del objeto
                if (campo.getName() == "linea") {
                    objeto.setLinea(linea);
                }
                if (campo.getName() == "origen") {
                    objeto.setOrigen(linea);
                }
                if (campo.getName() == "destino") {
                    objeto.setDestino(linea);
                }
                if (campo.getName() == "fecha") {
                    objeto.setFecha(linea);
                }
                if (campo.getName() == "hora") {
                    objeto.setHora(linea);
                }
                if (campo.getName() == "capacidad") {
                    objeto.setCapacidad(linea);
                }
                if (campo.getName() == "precio") {
                    objeto.setPrecio(linea);
                }
                //System.out.println( "\t"+linea+"\t\t");

            }
            //se inserta el objeto de vuelos en la lista de vuelos
            listaVuelos.add(objeto);
            //System.out.println( "");
        }
        //listaVuelos. add(objeto);
    } catch (IOException io) {
        System.out.println(io.getMessage());
    } catch (JDOMException jdomex) {
        System.out.println(jdomex.getMessage());
    } // se retorna la lista de vuelos
    return listaVuelos;

}

From source file:migrationextraction.MainWindowUI.java

private void processBasicInfoSheet(XSSFWorkbook wb) throws InvalidFormatException {
    try {/*from w w w  .ja v  a  2s .  c o  m*/
        XSSFSheet sheet = wb.getSheet("1. Supplier Basic Info");
        CTWorksheet ctws = sheet.getCTWorksheet();
        /*String xml10pattern = "[^"
            + "\u0009\r\n"
            + "\u0020-\uD7FF"
            + "\uE000-\uFFFD"
            + "\ud800\udc00-\udbff\udfff"
            + "]";
        String xml = ctws.toString().replaceAll(xml10pattern, "");*/
        //Get embedded objects positions.
        SAXBuilder saxB = new SAXBuilder();
        org.jdom2.Document doc = saxB.build(new StringReader(ctws.toString()));

        List<OleObject> oleObjects = new ArrayList<>();
        List<Element> elements = doc.getRootElement().getChildren();
        elements.stream().forEach((element) -> {
            if (element.getName().equals("oleObjects")) {
                element.getChildren();
                getXMLUntilOle(element.getContent(), 0);
                //Get content
                System.out.println("");
                //for(Content content:element.getContent())
            }
        });
    } catch (JDOMException | IOException ex) {
        Logger.getLogger(MainWindowUI.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:mil.tatrc.physiology.datamodel.doxygen.XSDToDoxygen.java

License:Open Source License

private void parse() throws Exception {
    SAXBuilder jdomBuilder = new SAXBuilder();
    xsdDocument = jdomBuilder.build(inputFile);
    schemaElement = xsdDocument.getRootElement();
    if (!XS.equals(schemaElement.getNamespace().getURI())) {
        throw new Exception("Unexpected namespace: " + schemaElement.getNamespace());
    }//from   w  w w  .  j a va2  s .  c  om
}

From source file:model.advertisement.AbstractAdvertisement.java

License:Open Source License

/**
 * Construct and initialize the class with a string in XML format.
 * @param XML/* www.  ja  v  a  2s .  com*/
 */
public AbstractAdvertisement(String XML) {
    this();
    SAXBuilder saxBuilder = new SAXBuilder();
    Reader stringReader = new StringReader(XML);
    Element root = null;
    try {
        root = saxBuilder.build(stringReader).getRootElement();
    } catch (JDOMException e) {
        System.err.println("Parse problem in " + this.getAdvType());
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    initialize(root);
}

From source file:Model.ConsultarXML.java

/***
 * mtodo para contar las etiquetas o nodos principales de un archivo XML
 * @param Documento ruta del documento que se leera, usar MateriasPath
 * @return cantidad de etiquetas hijo que tiene el documento
 *//* w w w. j av a 2  s  .co m*/
public static int ContarEtiquetas(String Documento, String nivel) throws JDOMException, IOException, Exception {

    SAXBuilder builder = new SAXBuilder();
    org.jdom2.Document doc = builder.build(Documento);
    Element nodo = doc.getRootElement();
    List<Element> nodos;

    if (!nivel.equals("")) {
        nodo = elementoNodo(nivel, nodo.getChildren());
    }
    return nodo.getChildren().size();

}