Example usage for org.jdom2.input SAXBuilder SAXBuilder

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

Introduction

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

Prototype

public SAXBuilder() 

Source Link

Document

Creates a new JAXP-based SAXBuilder.

Usage

From source file:ch.rotscher.maven.plugins.InstallWithVersionOverrideMojo.java

License:Apache License

private void replaceVersion(File originalPomFile, File newPomFile, String newVersion)
        throws IOException, JDOMException {

    //we assume that the version of "internal" dependencies are declared with ${project.version}
    FileWriter writer = new FileWriter(newPomFile);
    SAXBuilder parser = new SAXBuilder();
    XMLOutputter xmlOutput = new XMLOutputter();
    // display nice nice
    xmlOutput.setFormat(Format.getPrettyFormat());

    //parse the document
    Document doc = parser.build(originalPomFile);
    Element versionElem = findVersionElement(doc);
    versionElem.setText(newVersion);//  ww  w  .  j  a va 2s . c o m
    xmlOutput.output(doc, writer);
    writer.flush();
    writer.close();
}

From source file:ch.unifr.diuf.diva.did.Script.java

License:Open Source License

/**
 * Loads an XML script// w  ww . j a  v  a 2 s . c om
 * @param fname file name of the script
 * @throws JDOMException if the XML is not correctly formated
 * @throws IOException if there is a problem to read the XML
 */
public Script(String fname) throws JDOMException, IOException {
    SAXBuilder builder = new SAXBuilder();
    Document xml = builder.build(new File(fname));
    root = xml.getRootElement();
    scriptName = fname;

    addCommand("image", new ImageCreator(this));
    addCommand("alias", new Alias(this));
    addCommand("print", new TextPrinter(this));
    addCommand("apply-fade", new FadeGradients(this));
    addCommand("gradient-degradations", new NoiseGradients(this));
    addCommand("manual-gradient-degradations", new ManualGradientModification(this));
    addCommand("apply-mix", new MixImages(this));
    addCommand("save", new SaveImage(this));
    addCommand("delete", new DeleteImage(this));
    addCommand("pepper-salt", new PepperSalt(this));
    addCommand("gaussian-noise", new GaussianNoise(this));
    addCommand("selective-blur", new SelectiveBlur(this));
    addCommand("selective-hv-blur", new SelectiveHVBlur(this));
    addCommand("calc", new Calc(this));
    addCommand("result", new Result(this));
    addCommand("square-dist", new SquareDiff(this));
    addCommand("abs-dist", new AbsDiff(this));
    addCommand("gradient-diff", new CompareOrientations(this));
    addCommand("co-occurences", new CoOcMatrix(this));
    addCommand("non-null-mean", new NonNullMean(this));
    addCommand("variance", new Variance(this));
    addCommand("correlation", new Correlation(this));
    addCommand("scaled-difference", new ScaledDifference(this));
    addCommand("scale-offset-ind-dist", new ScaleOffsetInvDist(this));
    addCommand("decrease-max-contrast", new DecreaseMaxContrast(this));
}

From source file:Codigo.XMLReader.java

/**
 * Metodo utilizado para cargar todos los estadios del mundial Brasil 2014
 * desde un documento XML que contiene informacion de cada uno de ellos
 * @return Lista con los estadios del mundial
 *///from w w  w .ja  va 2s.c o m
public ListaEstadios cargarListaDeEstadios() {

    // Se crea la lista con los estadios que se va a retornar
    ListaEstadios listaEstadios = new ListaEstadios();
    //Se crea un SAXBuilder para poder parsear el archivo
    SAXBuilder builder = new SAXBuilder();

    try {
        File xmlFile = new File(getClass().getResource("/XML/Estadios.xml").toURI());
        //Se crea el documento a traves del archivo
        Document document = (Document) builder.build(xmlFile);
        //Se obtiene la raiz 'tables'
        Element raizXML = document.getRootElement();
        //Se obtiene la lista de hijos de la raiz 'Estadios'
        List list = raizXML.getChildren("Estadio");

        //Se recorre la lista de hijos de 'tables'
        for (int i = 0; i < list.size(); i++) {
            //Se obtiene el elemento 'Estadio'
            Element estadio = (Element) list.get(i);

            //Se obtiene el valor que esta entre los tags '<Nombre></Nombre>'
            String nombreEstadio = estadio.getChildText("Nombre");
            //Se obtiene el valor que esta entre los tags '<Ciudad></Ciudad>'
            String ciudadEstadio = estadio.getChildText("Ciudad");
            //Se obtiene el valor que esta entre los tags '<Capacidad></Capacidad>'
            int capacidadEstadio = Integer.parseInt(estadio.getChildTextTrim("Capacidad"));

            // Se crea un NodoEstadio con la informacion del estadio.
            NodoEstadio nuevoEstadio = new NodoEstadio(nombreEstadio, ciudadEstadio, capacidadEstadio);
            // Se inserta el nuevo estadio en la lista de estadios
            listaEstadios.insertarAlFinal(nuevoEstadio);
        }
        return listaEstadios;

    } catch (IOException | JDOMException | URISyntaxException io) {
        System.out.println(io.getMessage());
        return null;
    }
}

From source file:Codigo.XMLReader.java

/**
 * Metodo utilizado para cargar del XML la lisa de equipos que participan
 * en el mundial/* w  w  w .  j a v a2 s .  co m*/
 * @return Lista con los equipos participantes
 */
public ListaEquipos cargarListaEquipos() {

    // Se crea la lista con los equipos que se va a retornar
    ListaEquipos listaEquipos = new ListaEquipos();
    //Se crea un SAXBuilder para poder parsear el archivo
    SAXBuilder builder = new SAXBuilder();

    try {
        File xmlFile = new File(getClass().getResource("/XML/Equipos.xml").toURI());
        //Se crea el documento a traves del archivo
        Document document = (Document) builder.build(xmlFile);
        //Se obtiene la raiz 'Equipos'
        Element raizXML = document.getRootElement();

        //Se obtiene la lista de hijos de la raiz 'Equipos' (Todos los equipos del mundial)
        List listEquipos = raizXML.getChildren("Equipo");

        //Se recorre la lista de hijos de 'Equipos'
        for (int i = 0; i < listEquipos.size(); i++) {
            //Se obtiene el elemento 'equipo'
            Element equipo = (Element) listEquipos.get(i);
            // Se obtienen los datos del equipo actual
            String nombreEquipo = equipo.getChildText("Nombre");
            String nombreEntrenador = equipo.getChildText("Entrenador");
            int partidosJugados = Integer.parseInt(equipo.getChildTextTrim("PartidosJugados"));
            int partidosGanados = Integer.parseInt(equipo.getChildTextTrim("PartidosGanados"));
            int partidosEmpatados = Integer.parseInt(equipo.getChildTextTrim("PartidosEmpatados"));
            int partidosPerdidos = Integer.parseInt(equipo.getChildTextTrim("PartidosPerdidos"));
            int golesAFavor = Integer.parseInt(equipo.getChildTextTrim("GolesAFavor"));
            int golesEnContra = Integer.parseInt(equipo.getChildTextTrim("GolesEnContra"));
            int golDiferencia = Integer.parseInt(equipo.getChildTextTrim("GolDiferencia"));
            int puntos = Integer.parseInt(equipo.getChildTextTrim("Puntos"));
            // Se obtiene la lista de jugadores con su informacion del XML
            List listJugadores = equipo.getChild("Jugadores").getChildren("Jugador");

            // Se crea la lista de jugadores que va a contener el equipo actual
            ListaJugadores jugadores = new ListaJugadores();

            // Se recorre la lista de jugadores
            for (int j = 0; j < listJugadores.size(); j++) {
                // Se obtiene el jugador 'j' de la lista de Jugadores
                Element jugador = (Element) listJugadores.get(j);
                // Se obtienen los datos del jugador 'j'
                String nombreJugador = jugador.getChildText("Nombre");
                int numeroCamiseta = Integer.parseInt(jugador.getChildTextTrim("NumeroCamiseta"));
                String posicion = jugador.getChildTextTrim("Posicion");
                int edad = Integer.parseInt(jugador.getChildTextTrim("Edad"));
                int estatura = Integer.parseInt(jugador.getChildTextTrim("Estatura"));
                int goles = Integer.parseInt(jugador.getChildTextTrim("Goles"));

                //Se crea un nuevo NodoJugador donde se va a almacenar el jugador
                NodoJugador jugadorNuevo = new NodoJugador(nombreJugador, posicion, edad, estatura,
                        numeroCamiseta, goles);

                // Se inserta el nuevo NodoJugador en la lista de jugadores
                jugadores.insertarOrdenadoPorEdad(jugadorNuevo);
            }

            // Se crea un nuevo NodoEquipo que almacena la informacion del equipo actual
            NodoEquipo equipoActual = new NodoEquipo(nombreEquipo, nombreEntrenador, jugadores, partidosJugados,
                    partidosGanados, partidosEmpatados, partidosPerdidos, golesAFavor, golesEnContra,
                    golDiferencia, puntos);

            // Se inserta el NodoEquipo actual en la lista de equipos
            listaEquipos.insertarOrdenado(equipoActual);
        }
        // Retorna la lista de todos los equipos
        return listaEquipos;

    } catch (IOException | JDOMException | URISyntaxException io) {
        System.out.println(io.getMessage());
        return null;
    }
}

From source file:Codigo.XMLReader.java

/**
 * Metodo utilizado para crear los grupos del mundial con la informacion de todos
 * los encuentros por grupo/*from  w  ww  .  ja  va  2s.  c  om*/
 * @param pEquipos equipos participantes del mundial
 * @param pEstadios estadio del mundial
 * @return lista de los grupos del mundial
 */
public ListaGrupos cargarCalendarioYGrupos(ListaEquipos pEquipos, ListaEstadios pEstadios) {

    // Formato que se va a establecer en la creacion de cada fecha
    SimpleDateFormat formatoFecha = new SimpleDateFormat("d/M/yy h:mm a");
    // Se crea la lista de los Grupos del mundial, que se va a retornar
    ListaGrupos listaDeGrupos = new ListaGrupos();
    //Se crea un SAXBuilder para poder parsear el archivo
    SAXBuilder builder = new SAXBuilder();

    try {
        File xmlFile = new File(getClass().getResource("/XML/CalendarioGrupos.xml").toURI());
        //Se crea el documento a traves del archivo
        Document document = (Document) builder.build(xmlFile);
        //Se obtiene la raiz 'Grupos'
        Element raizXML = document.getRootElement();

        //Se obtiene la lista de hijos de la raiz 'Grupos' (Todos los grupos del mundial)
        List listaGruposXML = raizXML.getChildren("Grupo");

        // RECORRE LA LISTA DE GRUPOS DEL MUNDIAL
        for (int i = 0; i < listaGruposXML.size(); i++) {
            //Se obtiene el elemento 'Grupo' en la posicion i de la lista
            Element grupo = (Element) listaGruposXML.get(i);

            // Obtengo el atributo con la letra del grupo
            char letraDelGrupo = grupo.getAttributeValue("letra").charAt(0);

            // Se obtine la lista de los equipos que conforma el grupo
            List selecciones = grupo.getChild("Equipos").getChildren("Equipo");
            // Se crea un arreglo que almacenara las selecciones integrantes
            NodoEquipo[] equiposDelGrupo = new NodoEquipo[selecciones.size()];
            // RECORRE LA LISTA DE EQUIPOS PERTENECIENTES A ESTE GRUPO
            for (int j = 0; j < selecciones.size(); j++) {
                Element equipo = (Element) selecciones.get(j);
                // Obtiene el nombre del equipo 'j'
                NodoEquipo nombreDelEquipo = pEquipos.getNodoEquipo(equipo.getText());
                // Inserta nombre del equipo, en el arreglo de equiposDelGrupo
                equiposDelGrupo[j] = nombreDelEquipo;
            }

            // SE CREA LA LISTA QUE ALMACENARA LOS ENCUENTROS DEL GRUPO                
            ListaCalendario calendarioDelGrupo = new ListaCalendario();
            // Se obtiene la lista de todo los Encuentros correspondientes al grupo
            List listaDeEncuentros = grupo.getChild("Encuentros").getChildren("Partido");
            // RECORRE LA LISTA DE PARTIDOS CORRESPONDIENTES A LOS EQUIPOS DEL GRUPO ACTUAL
            for (int j = 0; j < listaDeEncuentros.size(); j++) {
                Element partido = (Element) listaDeEncuentros.get(j);

                // Obtiene los datos de fecha y hora del encuentro
                String fechaDelPartido = partido.getChildText("Fecha");
                String horaDelPartido = partido.getChildText("Hora");
                Date fechaYHora = formatoFecha.parse(fechaDelPartido + " " + horaDelPartido);

                // Obtiene los datos de condiciones climaticas del encuentro
                String humedad = partido.getChildText("Humedad");
                String velocidadViento = partido.getChildText("VelocidadViento");
                String temperatura = partido.getChildText("Temperatura");
                String condicionClimatica = partido.getChildText("CondicionClimatica");

                // Obtiene el estadio sede del encuentro
                String nombreEstadioSede = partido.getChildText("Sede");
                NodoEstadio estadioSede = pEstadios.getNodoEstadio(nombreEstadioSede);

                // Obtiene los equipos casa y visita que se enfrentan en el encuentro
                String nombreEquipoCasa = partido.getChildText("EquipoCasa");
                NodoEquipo equipoCasa = pEquipos.getNodoEquipo(nombreEquipoCasa);
                String nombreEquipoVisita = partido.getChildText("EquipoVisita");
                NodoEquipo equipoVisita = pEquipos.getNodoEquipo(nombreEquipoVisita);

                // Obtiene la cantidad de goles por equipo, en el encuentro
                int golesCasa = Integer.parseInt(partido.getChild("GolesCasa").getAttributeValue("goles"));
                String anotadoresCasa = "";
                int golesVisita = Integer.parseInt(partido.getChild("GolesVisita").getAttributeValue("goles"));
                String anotadoresVisita = "";

                // COMPRUEBA SI HUBIERON ANOTACIONES, DE LOS LOCALES, PARA OBTENER LOS ANOTADORES
                if (golesCasa > 0) {
                    List anotadores = partido.getChild("GolesCasa").getChild("Anotadores")
                            .getChildren("Anotador");
                    // RECORRE LA LISTA PARA OBTENER LOS ANOTADORES Y EL MINUTO DEL GOL
                    for (int k = 0; k < anotadores.size(); k++) {
                        Element anotador = (Element) anotadores.get(k);
                        // OBTENGO LOS DATOS DEL ANOTADOR 'k'
                        String nombre = anotador.getChildText("Nombre");
                        String minuto = anotador.getChildText("Minuto");
                        if (k < (anotadores.size() - 1)) {
                            anotadoresCasa += minuto + '\'' + "  " + nombre + '\n';
                        } else {
                            anotadoresCasa += minuto + '\'' + "  " + nombre;
                        }
                    }
                }
                // COMPRUEBA SI HUBIERON ANOTACIONES, DE LA VISITA, PARA OBTENER LOS ANOTADORES
                if (golesVisita > 0) {
                    List anotadores = partido.getChild("GolesVisita").getChild("Anotadores")
                            .getChildren("Anotador");
                    // RECORRE LA LISTA PARA OBTENER LOS ANOTADORES Y EL MINUTO DEL GOL
                    for (int k = 0; k < anotadores.size(); k++) {
                        Element anotador = (Element) anotadores.get(k);
                        // OBTENGO LOS DATOS DEL ANOTADOR 'k'
                        String nombre = anotador.getChildText("Nombre");
                        String minuto = anotador.getChildText("Minuto");
                        if (k < (anotadores.size() - 1)) {
                            anotadoresVisita += minuto + '\'' + "  " + nombre + '\n';
                        } else {
                            anotadoresVisita += minuto + '\'' + "  " + nombre;
                        }
                    }
                }
                // Crea un nuevo nodo Encuentro y lo inserta en la lista de Calendario
                NodoEncuentro encuentro = new NodoEncuentro(fechaYHora, humedad, velocidadViento, temperatura,
                        estadioSede, equipoCasa, equipoVisita, golesCasa, golesVisita, anotadoresCasa,
                        anotadoresVisita, condicionClimatica);

                // Inserta el nuevo nodo en la lista de Encuentros
                calendarioDelGrupo.insertarOrdenadoPorFecha(encuentro);
            }
            // Crea un nodo Grupo con toda la informacion del grupo actual
            NodoGrupo grupoDelMundial = new NodoGrupo(letraDelGrupo, equiposDelGrupo, calendarioDelGrupo);
            // Inserta el grupo a la lista de grupos
            listaDeGrupos.insertarOrdenado(grupoDelMundial);
        }
        // Retorna la lista de todos los equipos
        return listaDeGrupos;

    } catch (IOException | JDOMException | URISyntaxException | ParseException io) {
        System.out.println(io.getMessage());
        return null;
    }
}

From source file:codigoFonte.Sistema.java

public boolean addUser(User u) throws IOException {

    boolean success = false, matriculaExists = false;
    File file = new File("Sistema.xml");
    Document newDocument = null;/*w ww .  j a v a 2s  .co  m*/
    Element root = null;
    Attribute matricula = null, nome = null, tipo = null, senha = null;
    Element user = null;

    if (u.getTipo().isEmpty() || u.getTipo().isEmpty() || u.getPassword().isEmpty()) {
        return success;
    }

    if (file.exists()) {
        SAXBuilder builder = new SAXBuilder();
        try {
            newDocument = builder.build(file);
        } catch (JDOMException ex) {
            Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
        }
        root = newDocument.getRootElement();
    } else {
        root = new Element("sistema");

        newDocument = new Document(root);
    }

    if (root.getChildren().size() > 0) {
        List<Element> listUsers = root.getChildren();
        for (Element a : listUsers) {
            if (a.getAttributeValue("matrcula").equals(u.getMatricula())) {
                matriculaExists = true;
            }
        }
    }

    if (!matriculaExists) {
        user = new Element("user");

        matricula = new Attribute("matrcula", this.newId());
        tipo = new Attribute("tipo", u.getTipo());
        nome = new Attribute("nome", u.getNome());
        senha = new Attribute("senha", u.getPassword());

        user.setAttribute(matricula);
        user.setAttribute(nome);
        user.setAttribute(tipo);
        user.setAttribute(senha);
        //user.setAttribute(divida);

        root.addContent(user);

        success = true;
    }
    //        

    XMLOutputter out = new XMLOutputter();

    try {
        FileWriter arquivo = new FileWriter(file);
        out.output(newDocument, arquivo);
    } catch (IOException ex) {
        Logger.getLogger(Sistema.class.getName()).log(Level.SEVERE, null, ex);
    }

    return success;
}

From source file:codigoFonte.Sistema.java

public boolean editarUser(User u) {
    File file = new File("Sistema.xml");
    Document newDocument = null;//from   ww  w .  ja  va 2  s .c om
    Element root = null;
    boolean success = false;

    if (file.exists()) {
        SAXBuilder builder = new SAXBuilder();
        try {
            newDocument = builder.build(file);
        } catch (JDOMException ex) {
            Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
        }
        root = newDocument.getRootElement();
    }

    List<Element> listusers = root.getChildren();
    for (Element e : listusers) {
        if (e.getAttributeValue("matrcula").equals(u.getMatricula())) {
            e.getAttribute("nome").setValue(u.getNome());
            e.getAttribute("tipo").setValue(u.getTipo());
            e.getAttribute("senha").setValue(u.getPassword());

            success = true;

            XMLOutputter out = new XMLOutputter();

            try {
                FileWriter arquivo = new FileWriter(file);
                out.output(newDocument, arquivo);
            } catch (IOException ex) {
                Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
            }
            return success;
        }
    }
    return success;
}

From source file:codigoFonte.Sistema.java

public ArrayList<User> listarUser() {
    File file = new File("Sistema.xml");
    Document newDocument = null;/*from w ww .ja va 2  s .c o  m*/
    Element root = null;
    ArrayList<User> users = new ArrayList<User>();
    ;
    ArrayList<Livro> livros = new ArrayList<Livro>();

    if (file.exists()) {
        SAXBuilder builder = new SAXBuilder();
        try {
            newDocument = builder.build(file);
        } catch (JDOMException ex) {
            Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
        }
        root = newDocument.getRootElement();
    } else {
        root = new Element("sistema");

        newDocument = new Document(root);
    }

    List<Element> listusers = root.getChildren();
    for (Element e : listusers) {
        User user = new User(null, null, null, null);
        List<Element> listlivro = e.getChildren("livro");
        List<Element> historico = e.getChildren("histrico");

        if (!listlivro.isEmpty())

            for (Element l : listlivro) {
                Livro livro = new Livro(null, null, null, 0);
                livro.setAutor(l.getAttributeValue("autor"));
                livro.setEditora(l.getAttributeValue("editora"));
                livro.setTitulo(l.getAttributeValue("ttulo"));
                livros.add(livro);
            }

        //List<Element> historico = e.getChildren("histrico");
        ArrayList<Livro> historicoObjeto = new ArrayList<Livro>();
        if (!historico.isEmpty()) {
            for (Element h : historico) {
                Livro livroHistorico = new Livro(null, null, null, 0);
                livroHistorico.setAutor(h.getAttributeValue("autor"));
                livroHistorico.setEditora(h.getAttributeValue("editora"));
                livroHistorico.setTitulo(h.getAttributeValue("ttulo"));
                historicoObjeto.add(livroHistorico);
            }
        }

        user.setMatricula(e.getAttributeValue("matrcula"));
        user.setNome(e.getAttributeValue("nome"));
        user.setTipo(e.getAttributeValue("tipo"));
        user.setLivros(livros);

        users.add(user);
    }
    return users;
}

From source file:codigoFonte.Sistema.java

public User pesquisarUser(String matricula) {
    File file = new File("Sistema.xml");
    Document newDocument = null;//from w  w w .j a  v a  2s  .  c  o  m
    Element root = null;
    User user = null;

    if (file.exists()) {
        SAXBuilder builder = new SAXBuilder();
        try {
            newDocument = builder.build(file);
        } catch (JDOMException ex) {
            Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
        }
        root = newDocument.getRootElement();
    } else {
        root = new Element("sistema");

        newDocument = new Document(root);
    }

    List<Element> listusers = root.getChildren();
    for (Element e : listusers) {
        if (e.getAttributeValue("matrcula").equals(matricula)) {
            List<Element> listlivros = e.getChildren("livro");
            user = new User(null, null, null, null);
            if (!listlivros.isEmpty()) {
                for (Element l : listlivros) {
                    Livro livro = new Livro(null, null, null, 0);
                    livro.setAutor(l.getAttributeValue("autor"));
                    livro.setEditora(l.getAttributeValue("editora"));
                    livro.setTitulo(l.getAttributeValue("ttulo"));
                    livro.setEntrega(l.getAttributeValue("dataEntrega"));
                    livro.setAluguel(l.getAttributeValue("dataAluguel"));
                    livro.setId(l.getAttributeValue("id"));
                    user.getLivros().add(livro);
                }
            }
            List<Element> historico = e.getChildren("historico");
            if (!historico.isEmpty()) {
                for (Element h : historico) {
                    Livro livroHistorico = new Livro(null, null, null, 0);
                    livroHistorico.setAutor(h.getAttributeValue("autor"));
                    livroHistorico.setEditora(h.getAttributeValue("editora"));
                    livroHistorico.setTitulo(h.getAttributeValue("ttulo"));
                    livroHistorico.setEntrega(h.getAttributeValue("dataEntrega"));
                    livroHistorico.setAluguel(h.getAttributeValue("dataAluguel"));
                    livroHistorico.setId(h.getAttributeValue("id"));
                    user.getHistorico().add(livroHistorico);
                }
            }
            user.setMatricula(matricula);
            user.setTipo(e.getAttributeValue("tipo"));
            user.setNome(e.getAttributeValue("nome"));
            user.setPassword(e.getAttributeValue("senha"));

            return user;
        }
    }
    return user;
}

From source file:codigoFonte.Sistema.java

public boolean removeUser(User u) {
    File file = new File("Sistema.xml");
    Document newDocument = null;/*from w  w w  . ja v  a 2s  . c o m*/
    Element root = null;
    Element user = null;
    boolean success = false;

    if (file.exists()) {
        SAXBuilder builder = new SAXBuilder();
        try {
            newDocument = builder.build(file);
        } catch (JDOMException ex) {
            Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
        }
        root = newDocument.getRootElement();
    } else {
        root = new Element("sistema");

        newDocument = new Document(root);
    }

    List<Element> listusers = root.getChildren("user");
    for (Element e : listusers) {
        if (e.getAttributeValue("matrcula").equals(u.getMatricula()) && e.getChildren("livro").size() == 0) {
            root.removeContent(e);

            XMLOutputter out = new XMLOutputter();

            try {
                FileWriter arquivo = new FileWriter(file);
                out.output(newDocument, arquivo);
            } catch (IOException ex) {
                Logger.getLogger(Sistema.class.getName()).log(Level.SEVERE, null, ex);
            }

            success = true;
            return success;
        }
    }
    return success;
}