Example usage for org.jdom2 Document getRootElement

List of usage examples for org.jdom2 Document getRootElement

Introduction

In this page you can find the example usage for org.jdom2 Document getRootElement.

Prototype

public Element getRootElement() 

Source Link

Document

This will return the root Element for this Document

Usage

From source file:Api.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w w w .j a v  a2  s .  co  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("Content-Type: text/javascript");
    PrintWriter out = response.getWriter();

    // Se crea un SAXBuilder para poder parsear el archivo
    SAXBuilder builder = new SAXBuilder();
    File xmlFile = new File("Config.xml");

    try {
        //Se parcea el archivo xml para crear el documento 
        //que se va a tratar.
        Document documento = (Document) builder.build(xmlFile);
        // Se obtiene la raiz del documento. En este caso 'cruisecontrol'
        Element rootNode = documento.getRootElement();

        //            // Obtengo el tag "info" como nodo raiz para poder trabajar 
        //            // los tags de ste.
        //            Element rootNode_Level2 = rootNode.getChild("info");
        //            // Obtengo los nodos "property" del tag info y los almaceno en
        //            // una lista.
        //            List<Element> lista = rootNode_Level2.getChildren("property");
        //
        //            //Imprimo por consola la lista.
        //            for (int i = 0; i < lista.size(); i++) {
        //                System.out.println(((Element) lista.get(i)).getAttributeValue("value"));
        //            }
        // out.println("<!DOCTYPE html>");
        Map<String, Object> actions = new LinkedHashMap<String, Object>();

        for (Element action : rootNode.getChildren()) {

            ArrayList<Map> methods = new ArrayList<Map>();

            for (Element method : action.getChildren()) {

                Map<String, Object> md = new LinkedHashMap<String, Object>();

                if (method.getAttribute("len") != null) {

                    md.put("name", method.getName());
                    md.put("len", method.getAttributeValue("len"));

                } else {

                    md.put("name", method.getName());
                    md.put("params", method.getAttributeValue("params"));

                }

                if (method.getAttribute("formHandler") != null && method.getAttribute("formHandler") != null) {

                    md.put("formHandler", true);

                }

                methods.add(md);
            }

            actions.put(action.getName(), methods);
        }

    } catch (IOException io) {
        System.out.println(io.getMessage());
    } catch (JDOMException jdomex) {
        System.out.println(jdomex.getMessage());
    } finally {
        out.close();
    }

}

From source file:AL_gui.java

License:Apache License

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    // TODO add your handling code here:
    try {//from  ww  w .j av  a 2 s.  com
        String nnetName = JOptionPane.showInputDialog(jButton3, "Enter a filename, excluding extention.",
                "ANNeML Wizard", JOptionPane.QUESTION_MESSAGE);
        if (nnetName == " ") {
            JOptionPane.showMessageDialog(null, "An input value must be entered.");
        }

        Element nnet = new Element("NNETWORK");
        nnet.setAttribute(new Attribute("noNamespaceSchemaLocation", "ANNeML.xsd",
                Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance")));
        nnet.setAttribute(new Attribute("NNET_NAME", nnetName));
        Document doc = new Document(nnet);

        String subnnets = JOptionPane.showInputDialog(jButton3, "How many SUBNET(s)?", "ANNeML Wizard",
                JOptionPane.QUESTION_MESSAGE);
        if (subnnets == " ") {
            JOptionPane.showMessageDialog(null, "An input value must be entered.");
        }
        int numSubs = java.lang.Integer.parseInt(subnnets);
        int i = 0;
        do {
            Element subnet = new Element("SUBNET");
            String learningRate = JOptionPane.showInputDialog(jButton3, "SUBNET learning rate(eta)?",
                    "ANNeML Wizard", JOptionPane.QUESTION_MESSAGE);
            if (learningRate == " ") {
                JOptionPane.showMessageDialog(null, "An input value must be entered.");
            }
            subnet.setAttribute(new Attribute("NNET_V2", learningRate));
            subnet.setAttribute(new Attribute("SNET_NAME", nnetName + "-subnet" + String.valueOf(i + 1)));
            subnet.setAttribute(new Attribute("ADJUST_LOCK", "0"));

            String input_layers = JOptionPane.showInputDialog(jButton3,
                    "How many <<INPUT>> LAYERS(s) in this subnet?", "ANNeML Wizard",
                    JOptionPane.QUESTION_MESSAGE);
            if (input_layers == " ") {
                JOptionPane.showMessageDialog(null, "An input value must be entered.");
            }
            int numInLayers = java.lang.Integer.parseInt(input_layers);
            int x = 0;
            do {
                Element inLayer = new Element("LAYER");
                inLayer.setAttribute(new Attribute("LAYER_NAME", "INPUT"));
                String transferFunc = JOptionPane.showInputDialog(jButton3,
                        "Which transfer function for this LAYER? 1(hyberbolic tangent) or 2(logarithmic sigmoid)",
                        "ANNeML Wizard", JOptionPane.QUESTION_MESSAGE);
                if (transferFunc == " ") {
                    JOptionPane.showMessageDialog(null, "An input value must be entered.");
                }
                inLayer.setAttribute(new Attribute("TRANSFER_FUNCTION", transferFunc));
                String inNodes = JOptionPane.showInputDialog(jButton3,
                        "How many NEURODE(s) in this <<INPUT>> LAYER?", "ANNeML Wizard",
                        JOptionPane.QUESTION_MESSAGE);
                if (inNodes == " ") {
                    JOptionPane.showMessageDialog(null, "An input value must be entered.");
                }
                int numInNodes = java.lang.Integer.parseInt(inNodes);
                int y = 0;
                do {
                    Element node = new Element("NEURODE");
                    node.setAttribute(
                            new Attribute("N_ID", "IN" + String.valueOf(x + 1) + String.valueOf(y + 1)));
                    node.setAttribute(new Attribute("ACTIVE", "-1"));
                    node.setAttribute(new Attribute("ACTIVITY", "0.0"));
                    node.setAttribute(new Attribute("BIAS", "0.0"));
                    node.setAttribute(new Attribute("CNAME", "Input node#" + String.valueOf(y + 1)));
                    node.setAttribute(new Attribute("NNET_V4", "0.0"));
                    Element inSynapse = new Element("SYNAPSE");
                    inSynapse.setAttribute(new Attribute("WEIGHT", "1.00"));
                    inSynapse.setAttribute(new Attribute("ORG_NEURODE", "INPUT"));
                    node.addContent(inSynapse);
                    inLayer.addContent(node);
                    y++;
                } while (y < numInNodes);
                subnet.addContent(inLayer);
                x++;
            } while (x < numInLayers);

            String hidden_layers = JOptionPane.showInputDialog(jButton3,
                    "How many <<HIDDEN>> LAYERS(s) in this subnet?", "ANNeML Wizard",
                    JOptionPane.QUESTION_MESSAGE);
            if (hidden_layers == " ") {
                JOptionPane.showMessageDialog(null, "An input value must be entered.");
            }
            int numHLayers = java.lang.Integer.parseInt(hidden_layers);
            int z = 0;
            do {
                Element hLayer = new Element("LAYER");
                hLayer.setAttribute(new Attribute("LAYER_NAME", "HIDDEN"));
                String transferFunc = JOptionPane.showInputDialog(jButton3,
                        "Which transfer function for this LAYER? 1(hyberbolic tangent) or 2(logarithmic sigmoid)",
                        "ANNeML Wizard", JOptionPane.QUESTION_MESSAGE);
                if (transferFunc == " ") {
                    JOptionPane.showMessageDialog(null, "An input value must be entered.");
                }
                hLayer.setAttribute(new Attribute("TRANSFER_FUNCTION", transferFunc));
                String hNodes = JOptionPane.showInputDialog(jButton3,
                        "How many NEURODE(s) in this <<HIDDEN>> LAYER?", "ANNeML Wizard",
                        JOptionPane.QUESTION_MESSAGE);
                if (hNodes == " ") {
                    JOptionPane.showMessageDialog(null, "An input value must be entered.");
                }
                int numhNodes = java.lang.Integer.parseInt(hNodes);
                int a = 0;
                do {
                    Random rnd = new Random();
                    Element node = new Element("NEURODE");
                    node.setAttribute(
                            new Attribute("N_ID", "N" + String.valueOf(z + 1) + String.valueOf(a + 1)));
                    node.setAttribute(new Attribute("ACTIVE", "-1"));
                    node.setAttribute(new Attribute("ACTIVITY", "0.0"));
                    node.setAttribute(new Attribute("BIAS", getRandomValue(rnd, low, high, decpl)));
                    node.setAttribute(new Attribute("CNAME", "Hidden node#" + String.valueOf(a + 1)));
                    node.setAttribute(new Attribute("NNET_V4", "0.0"));
                    hLayer.addContent(node);
                    a++;
                } while (a < numhNodes);
                subnet.addContent(hLayer);
                z++;
            } while (z < numHLayers);

            String output_layers = JOptionPane.showInputDialog(jButton3,
                    "How many <<OUTPUT>> LAYERS(s) in this subnet?", "ANNeML Wizard",
                    JOptionPane.QUESTION_MESSAGE);
            if (hidden_layers == " ") {
                JOptionPane.showMessageDialog(null, "An input value must be entered.");
            }
            int numOLayers = java.lang.Integer.parseInt(output_layers);
            int b = 0;
            do {
                Element oLayer = new Element("LAYER");
                oLayer.setAttribute(new Attribute("LAYER_NAME", "OUTPUT"));
                String transferFunc = JOptionPane.showInputDialog(jButton3,
                        "Which transfer function for this LAYER? 1(hyberbolic tangent) or 2(logarithmic sigmoid)",
                        "ANNeML Wizard", JOptionPane.QUESTION_MESSAGE);
                if (transferFunc == " ") {
                    JOptionPane.showMessageDialog(null, "An input value must be entered.");
                }
                oLayer.setAttribute(new Attribute("TRANSFER_FUNCTION", transferFunc));
                String oNodes = JOptionPane.showInputDialog(jButton3,
                        "How many NEURODE(s) in this <<OUTPUT>> LAYER?", "ANNeML Wizard",
                        JOptionPane.QUESTION_MESSAGE);
                if (oNodes == " ") {
                    JOptionPane.showMessageDialog(null, "An input value must be entered.");
                }
                int numoNodes = java.lang.Integer.parseInt(oNodes);
                int d = 0;
                do {
                    Random rnd = new Random();
                    Element node = new Element("NEURODE");
                    node.setAttribute(
                            new Attribute("N_ID", "ON" + String.valueOf(b + 1) + String.valueOf(d + 1)));
                    node.setAttribute(new Attribute("ACTIVE", "-1"));
                    node.setAttribute(new Attribute("ACTIVITY", "0.0"));
                    node.setAttribute(new Attribute("BIAS", getRandomValue(rnd, low, high, decpl)));
                    node.setAttribute(new Attribute("CNAME", "Output node#" + String.valueOf(d + 1)));
                    node.setAttribute(new Attribute("NNET_V4", "0.0"));
                    oLayer.addContent(node);
                    d++;
                } while (d < numoNodes);
                subnet.addContent(oLayer);
                b++;
            } while (b < numOLayers);

            doc.getRootElement().addContent(subnet);
            i++;
        } while (i < numSubs);

        //generate fully interconnected SYNAPSE(s) for all NEURODE(s) within each SUBNET

        java.util.List subnets = XPath.newInstance("//SUBNET").selectNodes(doc);
        Iterator itSubslist = subnets.iterator();
        do {
            Element currentSnet = (Element) itSubslist.next();
            String snetName = currentSnet.getAttributeValue("SNET_NAME");
            //System.out.println(snetName);

            java.util.List Hnodes = XPath
                    .newInstance("//SUBNET[@SNET_NAME='" + snetName + "']/LAYER[@LAYER_NAME='HIDDEN']/NEURODE")
                    .selectNodes(doc);
            Iterator itHNodelist = Hnodes.iterator();
            do {
                Element node = (Element) itHNodelist.next();
                //System.out.println(node.getAttributeValue("N_ID"));
                java.util.List Inodes = XPath
                        .newInstance(
                                "//SUBNET[@SNET_NAME='" + snetName + "']/LAYER[@LAYER_NAME='INPUT']/NEURODE")
                        .selectNodes(doc);
                Iterator itNodelist = Inodes.iterator();
                do {
                    Element currentNode = (Element) itNodelist.next();
                    //System.out.println(currentNode.getAttributeValue("N_ID"));
                    Element hSynapse = new Element("SYNAPSE");
                    Random rnd = new Random();
                    hSynapse.setAttribute(new Attribute("WEIGHT", getRandomValue(rnd, low, high, decpl)));
                    hSynapse.setAttribute(new Attribute("ORG_NEURODE", currentNode.getAttributeValue("N_ID")));
                    node.addContent(hSynapse);
                } while (itNodelist.hasNext());
            } while (itHNodelist.hasNext());

            java.util.List Onodes = XPath
                    .newInstance("//SUBNET[@SNET_NAME='" + snetName + "']/LAYER[@LAYER_NAME='OUTPUT']/NEURODE")
                    .selectNodes(doc);
            Iterator itONodelist = Onodes.iterator();
            do {
                Element node = (Element) itONodelist.next();
                //System.out.println(node.getAttributeValue("N_ID"));
                java.util.List hnodes = XPath
                        .newInstance(
                                "//SUBNET[@SNET_NAME='" + snetName + "']/LAYER[@LAYER_NAME='HIDDEN']/NEURODE")
                        .selectNodes(doc);
                Iterator itNodelist = hnodes.iterator();
                do {
                    Element currentNode = (Element) itNodelist.next();
                    //System.out.println(currentNode.getAttributeValue("N_ID"));
                    Element hSynapse = new Element("SYNAPSE");
                    Random rnd = new Random();
                    hSynapse.setAttribute(new Attribute("WEIGHT", getRandomValue(rnd, low, high, decpl)));
                    hSynapse.setAttribute(new Attribute("ORG_NEURODE", currentNode.getAttributeValue("N_ID")));
                    node.addContent(hSynapse);
                } while (itNodelist.hasNext());
            } while (itONodelist.hasNext());

        } while (itSubslist.hasNext());

        // new XMLOutputter().output(doc, System.out);
        XMLOutputter xmlOutput = new XMLOutputter();

        // display nice nice
        xmlOutput.setFormat(Format.getPrettyFormat());
        xmlOutput.output(doc, System.out);
        xmlOutput.output(doc, new FileWriter(nnetName + ".xml"));

        System.out.println("File Saved!");

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

}

From source file:VraagServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //Bestandslocatie van de XML file. Later als parameter meegeven
    String xmlUrl = "file:///H:/NetBeansProjects/WebApplication1/GMFM.xml";

    PrintWriter out = new PrintWriter(response.getOutputStream());

    //Maakt HTML pagina aan
    out.println("<html>");
    out.println("<head><title>Formulier</title></head>");
    out.println("<body>");

    try {/*from  w ww . ja  v a 2s .  c o  m*/
        //Maakt een URL aan die naar het XML document wijst. En een builder die vervolgens een document opbouwt.
        URL theDoc = new URL(xmlUrl);
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(theDoc);

        // Geeft het root element (Formulier)
        Element root = document.getRootElement();

        /* Maakt een lijst aan waarin alle XML staat die tussen <uitleg> </uitleg> staat. 
         De lijst wordt vervolgens geitereerd totdat alle elementen uit de uitleg zijn geweest en in de html staan.*/
        List uitleg = root.getChildren("UITLEG");
        Iterator uitlegItr = uitleg.iterator();
        while (uitlegItr.hasNext()) {
            Object u = uitlegItr.next();
            Element beschrijving = (Element) u;
            out.println(beschrijving.getChildText("BESCHRIJVING"));
        }

        /* Maakt een lijst aan waarin alle XML staat die tussen <regel> </regel> staat. 
         De lijst wordt vervolgens geitereerd totdat alle elementen uit de regel zijn geweest.*/
        List vragen = root.getChildren("REGEL");
        Iterator itr = vragen.iterator();

        //Er wordt net zolang doorgegaan totdat de laatste vraag is bereikt. Alle vragen worden in een tabel gestopt.
        out.println("<table border =1>");
        out.println("<form >");
        while (itr.hasNext()) {
            Object o = itr.next();
            Element vraag = (Element) o;

            /*Hieronder worden de verschillende invoermogelijkheden opgeslagen dus bijvoorbeeld 4 checkbox buttons naast elkaar.
             Een variabele met NT erachter betekent dat deze een extra knop heeft voor niet getest.
             VALUES NOG TOEVOEGEN AAN VARIABELEN
             Uitbreiden indien nodig!!*/
            StringBuffer row = new StringBuffer("<tr>");
            //                

            /*De vraag wordt opgehaald en in de eerste kolom van de tabel gezet.
            Vervolgens wordt het antwoord opgehaald en wordt gekeken waarmee dit antwoord overeen komt. 
            Dit bepaald vervolgens hoeveel checkbox buttons/tekstvakken er gemaakt worden of dat er gewoon tekst afgedrukt wordt. 
            Uitbreiden als nodig!!!
            */
            row.append("<td>" + vraag.getChildText("VRAAG") + "</td>");
            String antwoord = vraag.getChildText("INVOERMOGELIJKHEID");

            if (antwoord.equals("driecheckbox")) {
                row.append("<td>" + "<input type=\"checkbox\" name=\"driecheckbox\" value=\"0\">"
                        + "<input type=\"checkbox\" name=\"driecheckbox\" value=\"0\">"
                        + "<input type=\"checkbox\" name=\"driecheckbox\" value=\"0\">");
            } else if (antwoord.equals("viercheckboxNT")) {
                row.append("<td>" + "<input type=\"checkbox\" name=\"viercheckboxNT\" value=\"0\" id=\"0\">"
                        + "<input type=\"checkbox\"name=\"viercheckboxNT\"value=\"1\"id=\"1\">"
                        + "<input type=\"checkbox\"name=\"viercheckboxNT\"value=\"2\"id=\"2\">"
                        + "<input type=\"checkbox\"name=\"viercheckboxNT\"value=\"3\"id=\"3\">"
                        + "<input type=\"checkbox\"name=\"viercheckboxNT\"value=\"\"id=\"4\">" + "</td>");

            } else if (antwoord.equals("vijfcheckbox")) {
                row.append("<td>" + "<input type=\"checkbox\" name=\"vijfcheckbox\" value=\"0\">"
                        + "<input type=\"checkbox\"name=\"vijfcheckbox\"value=\"1\">"
                        + "<input type=\"checkbox\"name=\"vijfcheckbox\"value=\"2\">"
                        + "<input type=\"checkbox\"name=\"vijfcheckbox\"value=\"3\">"
                        + "<input type=\"checkbox\"name=\"vijfcheckbox\"value=\"4\">");
            } else if (antwoord.equals("tekstvak")) {
                row.append("<td>" + "<INPUT TYPE=\"text\" NAME=\"tekstvak\" SIZE=\"13\" MAXLENGTH=\"20\">");
            } else {
                row.append("<td>" + antwoord);
            }
            //Hier wordt de regel uitgeprint in de html 
            out.println(row.toString());

        }

        //Sluiten van tabel en html 
        out.println("</table>");
        out.println("<input type=\"submit\" value=\"Formulier verzenden\">");
        String[] results = request.getParameterValues("viercheckboxNT");
        for (int i = 0; i < results.length; i++) {
            out.println(results[i]);
        }
        out.println("</form>");

        out.println("</body></html>");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (JDOMException e) {
        e.printStackTrace();
    } finally {
        out.close();
    }
}

From source file:agendavital.modelo.data.InicializarBD.java

public static void cargarXMLS() throws JDOMException, IOException, SQLException, ConexionBDIncorrecta {
    SAXBuilder builder = new SAXBuilder();
    File xmlFolder = new File("Noticias");
    File[] xmlFile = xmlFolder.listFiles();
    System.out.println("LONGITUD " + xmlFile.length);
    for (int i = 0; i < xmlFile.length; i++) {

        Document document = (Document) builder.build(xmlFile[i]);
        Element rootNode = document.getRootElement();
        List list = rootNode.getChildren("Noticia");
        for (Object list1 : list) {
            Element noticia = (Element) list1;
            List noticiaCampos = noticia.getChildren();
            String titulo = noticia.getChildTextTrim("titulo");

            String fecha = noticia.getChildTextTrim("fecha");

            String link = noticia.getChildTextTrim("link");

            String categorias = noticia.getChildTextTrim("categoria");

            String cuerpo = noticia.getChildTextTrim("cuerpo");

            List tags = noticia.getChildren("tag");
            ArrayList<String> etiquetas = new ArrayList<>();
            for (Object tags1 : tags) {
                Element tag = (Element) tags1;

                etiquetas.add(tag.getTextTrim());
            }/* w  ww . jav  a 2s  . c o m*/
            Noticia.Insert(titulo, link, fecha, categorias, cuerpo, etiquetas);
        }
    }
}

From source file:AIR.ResourceBundler.Xml.Resources.java

License:Open Source License

public void parse() throws JDOMException, IOException, ResourcesException {
    SAXBuilder builder = new SAXBuilder();
    File xmlFile = new File(_configFile);
    Document document = (Document) builder.build(xmlFile);
    Element rootElement = document.getRootElement();

    String attr = rootElement.getAttributeValue("name");
    name = (attr != null) ? attr : null;
    for (Element childEl : rootElement.getChildren()) {
        String childName = childEl.getName();
        if ("import".equalsIgnoreCase(childName)) {
            parseImport(childEl);//from   www . java2  s.c om
        } else if ("fileSet".equalsIgnoreCase(childName)) {
            parseFileSet(childEl);
        } else if ("remove".equalsIgnoreCase(childName)) {
            parseRemove(childEl);
        }

    }
}

From source file:app.simulation.Importer.java

License:MIT License

public void importXML() throws Exception {
    File file = new File(path);

    if (!file.exists())
        throw new FileNotFoundException(path);

    if (!getFileFormat().equalsIgnoreCase("xml"))
        throw new InvalidFileFormatException(getFileFormat());

    SAXBuilder saxBuilder = new SAXBuilder();
    Document document = saxBuilder.build(file);
    Element root = document.getRootElement();
    Element configuration = root.getChild("configuration");

    if (configuration != null) {

        String delayText = configuration.getChildText("delay");
        if (delayText == null)
            throw new AttributeNotFoundException("delay");

        String iterationsText = configuration.getChildText("iterations");
        if (iterationsText == null)
            throw new AttributeNotFoundException("iterations");

        String agentsText = configuration.getChildText("agents");
        if (agentsText == null)
            throw new AttributeNotFoundException("agents");

        String latticeSizeText = configuration.getChildText("latticeSize");
        if (latticeSizeText == null)
            throw new AttributeNotFoundException("latticeSize");

        String descriptionText = configuration.getChildText("description");
        if (descriptionText == null)
            throw new AttributeNotFoundException("description");

        int delay = Integer.parseInt(delayText);
        int iterations = Integer.parseInt(iterationsText);
        int agents = Integer.parseInt(agentsText);
        int latticeSize = Integer.parseInt(latticeSizeText);
        this.configuration = new Configuration(delay, iterations, agents, latticeSize, descriptionText);
    }//from www  .  j  a  v  a2 s .  co m

    Element initialCell = root.getChild("initialCell");

    if (initialCell != null) {

        String xText = initialCell.getChildText("x");
        if (xText == null)
            throw new AttributeNotFoundException("x");

        String yText = initialCell.getChildText("y");
        if (yText == null)
            throw new AttributeNotFoundException("y");

        String zText = initialCell.getChildText("z");
        if (zText == null)
            throw new AttributeNotFoundException("z");

        String stateText = initialCell.getChildText("state");
        if (stateText == null)
            throw new AttributeNotFoundException("state");

        Element colorElement = initialCell.getChild("color");
        if (colorElement == null)
            throw new AttributeNotFoundException("color");

        String rText = colorElement.getChildText("r");
        if (rText == null)
            throw new AttributeNotFoundException("r");

        String gText = colorElement.getChildText("g");
        if (gText == null)
            throw new AttributeNotFoundException("g");

        String bText = colorElement.getChildText("b");
        if (bText == null)
            throw new AttributeNotFoundException("b");

        int x = Integer.parseInt(xText);
        int y = Integer.parseInt(yText);
        int z = Integer.parseInt(zText);
        int state = Integer.parseInt(stateText);
        Color color = new Color(Integer.parseInt(rText), Integer.parseInt(gText), Integer.parseInt(bText));
        this.initialCell = new Cell(x, y, z, state, color);
    }

    Element tagRules = root.getChild("rules");
    rules = new ArrayList<Rule>();

    if (tagRules != null) {
        List<Element> elementRules = tagRules.getChildren("rule");

        if (elementRules.size() > 0) {

            for (Element rule : elementRules) {

                String neighbourhood = rule.getChildText("neighbourhood");
                if (neighbourhood == null)
                    throw new AttributeNotFoundException("neighbourhood");

                String stateText = rule.getChildText("state");
                if (stateText == null)
                    throw new AttributeNotFoundException("state");

                Element colorElement = rule.getChild("color");
                if (colorElement == null)
                    throw new AttributeNotFoundException("color");

                String rText = colorElement.getChildText("r");
                if (rText == null)
                    throw new AttributeNotFoundException("r");

                String gText = colorElement.getChildText("g");
                if (gText == null)
                    throw new AttributeNotFoundException("g");

                String bText = colorElement.getChildText("b");
                if (bText == null)
                    throw new AttributeNotFoundException("b");

                int state = Integer.parseInt(stateText);
                Color color = new Color(Integer.parseInt(rText), Integer.parseInt(gText),
                        Integer.parseInt(bText));

                rules.add(new Rule(neighbourhood, state, color));
            }
        }
    }

}

From source file:appmain.AppMain.java

private List<String> readXMLData(File xml) {
    try {//w  w w .  jav  a2 s. com
        List<String> transactions = new ArrayList<>();

        Document xmlDoc = jdomBuilder.build(xml);
        Element report = xmlDoc.getRootElement();

        ElementFilter filter = new ElementFilter("G_TR");
        Iterator<Element> c = report.getDescendants(filter);
        while (c.hasNext()) {
            Element e = c.next();
            transactions.add(processTransactionElement(e));
        }
        return transactions;
    } catch (JDOMException | IOException ex) {
        JOptionPane.showMessageDialog(null, "Hiba az XML fjl feldolgozsa kzben!\n"
                + ExceptionUtils.getStackTrace(ex) + "Fjl: " + xml.getAbsolutePath(), "Hiba",
                JOptionPane.ERROR_MESSAGE);
    }
    return null;
}

From source file:arquivo.Arquivo.java

public List busca(String nome, boolean completa, String nomeE) {
    SAXBuilder builder = new SAXBuilder();
    List<Element> retorna = new LinkedList<>();
    try {/*from   ww w. ja v a2 s  . c  om*/
        Document doc = builder.build(arquivo);
        Element root = (Element) doc.getRootElement();

        retorna = this.buscaInterna(root, completa, nome, nomeE);
    } catch (Exception e) {

    }
    return retorna;
}

From source file:arquivo.Arquivo.java

public String remove(String nome, String nomeE) {
    SAXBuilder builder = new SAXBuilder();
    List<Element> retorna = new LinkedList<>();

    try {//from  w  ww .j a v  a2s.  c  om
        Document doc = builder.build(arquivo);
        Element root = (Element) doc.getRootElement();

        List<Element> removido = buscaInterna(root, true, nome, nomeE);
        root.removeContent(removido.get(0));

        XMLOutputter xout = new XMLOutputter();
        OutputStream out = new FileOutputStream(arquivo);
        xout.output(doc, out);
        return "Documento alterado com sucesso!";
    } catch (Exception e) {
        e.printStackTrace();
    }

    return "n foi possivel remover " + nome;
}

From source file:arquivo.ArquivoF.java

public String add(String confSenha, String loing, String senha, String nome) {
    if (confSenha.equals(senha) && !loing.equals("") && !nome.equals("") && !senha.equals("")) {
        if (0 != busca(nome, true, "funcinario").size() && buscaLong(loing).size() != 0)
            return "erro nome ja cadastrado";
        SAXBuilder builder = new SAXBuilder();
        try {//from   w w w.  ja v  a  2  s. c  om
            Document doc = builder.build(arquivo);
            Element root = (Element) doc.getRootElement();

            Element funcionario = new Element("funcinario");

            Attribute nomeE = new Attribute("nome", nome);
            funcionario.setAttribute(nomeE);

            Element loingE = new Element("loing");
            loingE.setText(loing);
            funcionario.addContent(loingE);

            Element senhaE = new Element("senha");
            senhaE.setText(senha);
            funcionario.addContent(senhaE);

            root.addContent(funcionario);

            XMLOutputter xout = new XMLOutputter();
            OutputStream out = new FileOutputStream(arquivo);
            xout.output(doc, out);
            System.out.println("Documento alterado com sucesso!");

            return "cadastrado com suceso";
        } catch (Exception e) {

        }
    } else
        return "preemcha os compos corretamente";
    return "erro cadastral";
}