Example usage for org.jdom2 Element addContent

List of usage examples for org.jdom2 Element addContent

Introduction

In this page you can find the example usage for org.jdom2 Element addContent.

Prototype

@Override
public Element addContent(final Collection<? extends Content> newContent) 

Source Link

Document

Appends all children in the given collection to the end of the content list.

Usage

From source file:Question.java

License:Apache License

/**
 * Add the content of the question to the template.  This adds a string to one particular element of the XML
 * template./*  ww  w . j av a  2 s  .c  om*/
 * 
 * @param questionContent      We only allow the question content element of the question to vary dynamically.
 * @throws StoryException
 */
public void addQuestionContent(String questionContent) throws StoryException {
    // This should REALLY be done using Xpath, but Amazon's mturk doesn't use a prefix to their xmlns definition
    // and XPath maps this into the null namespace.

    logger.debug("getting the XML element for the QuestionContent...");
    Element question = root.getChild("Question", ns);
    if (question == null) {
        throw new StoryException("The XML template file doesn't contain a proper Question element");
    }
    Element qc = question.getChild("QuestionContent", ns);
    if (qc == null) {
        throw new StoryException("The XML template file doesn't contain a proper QuestionContent element");
    }
    Element txt = qc.getChild("Text", ns);
    if (txt == null) {
        throw new StoryException("The XML template file's QuestionContent element doesn't have a Text element");
    }

    logger.debug("adding the StoryText to the template XML...");
    txt.addContent(questionContent);
}

From source file:Question.java

License:Apache License

/**
 * This adds one radio button selection to a radio button based HIT template.  If the questionTemplateFile doesn't
 * contain a StyleSuggestion element containing "radiobutton", then this method won't work.
 * //from w  ww. jav a  2  s.  c o  m
 * @param radioButtonText
 * @param radioButtonIdentifier
 * @throws StoryException
 */
public void addRadioButtonSpecification(String radioButtonText, String radioButtonIdentifier)
        throws StoryException {
    // This should REALLY be done using Xpath, but Amazon's mturk doesn't use a prefix to their xmlns definition
    // and XPath maps this into the null namespace.
    logger.debug("getting the XML element for the Selection...");
    Element question = root.getChild("Question", null);
    if (question == null) {
        throw new StoryException("The XML template file doesn't contain a proper Question element");
    }
    Element answerSpecification = question.getChild("AnswerSpecification", null);
    if (answerSpecification == null) {
        throw new StoryException("The XML template file doesn't contain a proper AnswerSpecification element");
    }
    Element selectionAnswer = answerSpecification.getChild("SelectionAnswer", null);
    if (selectionAnswer == null) {
        throw new StoryException("The XML template file doesn't contain a proper SelectionAnswer element");
    }
    Element selections = selectionAnswer.getChild("Selections", null);
    if (selections == null) {
        throw new StoryException("The XML template file's QuestionContent element doesn't have a Text element");
    }

    // Adding in the namespace URI is the only way to keep JDOM2 from adding a null namespace to the element
    Element selection = new Element("Selection",
            "http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2005-10-01/QuestionForm.xsd");
    Element selectionIdentifier = new Element("SelectionIdentifier",
            "http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2005-10-01/QuestionForm.xsd");
    Element text = new Element("Text",
            "http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2005-10-01/QuestionForm.xsd");
    text.addContent(radioButtonText);
    selectionIdentifier.addContent(radioButtonIdentifier);
    selection.addContent(selectionIdentifier);
    selection.addContent(text);
    selections.addContent(selection);

}

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 {//  www .j  a va2s  .  co m
        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:Content.java

public void setRightClick(boolean isLibrary) {
    if (isLibrary) {
        playlist.setComponentPopupMenu(null);
        menu = new JPopupMenu();

        JMenuItem item1 = new JMenuItem("Edit Track");
        item1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                int row = playlist.getSelectedRow();
                if (row == -1) {
                    return;
                }//from  w w w.  j  a v a  2s .  c  o m

                songClicked = (Element) Library.getLib().get(row);

                Frame parentFrame = (Frame) SwingUtilities.windowForComponent(playlist);
                dialog = new JDialog(parentFrame);

                JPanel editPanel = new JPanel();
                editPanel.setLayout(new BoxLayout(editPanel, BoxLayout.PAGE_AXIS));

                JLabel songNameLabel = new JLabel("Song name");
                songName = new JTextField(songClicked.getChildText("name"));
                songName.setPreferredSize(new Dimension(200, 20));
                editPanel.add(songNameLabel);
                editPanel.add(songName);

                JLabel songArtistLabel = new JLabel("Artist");
                songArtist = new JTextField(songClicked.getChildText("artist"));
                songArtist.setPreferredSize(new Dimension(200, 20));
                editPanel.add(songArtistLabel);
                editPanel.add(songArtist);

                JLabel songAlbumLabel = new JLabel("Album");
                songAlbum = new JTextField(songClicked.getChildText("album"));
                songAlbum.setPreferredSize(new Dimension(200, 20));
                editPanel.add(songAlbumLabel);
                editPanel.add(songAlbum);

                JLabel songLocationLabel = new JLabel("Location");
                songLocation = new JTextField(songClicked.getChildText("url"));
                songLocation.setPreferredSize(new Dimension(200, 20));
                editPanel.add(songLocationLabel);
                editPanel.add(songLocation);

                JPanel buttons = new JPanel();

                JButton buttonEdit = new JButton("Save");
                buttons.add(buttonEdit);

                editPanel.add(buttonEdit);

                buttonEdit.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent ev) {
                        // edit song
                        songClicked.removeChild("name");
                        songClicked.removeChild("artist");
                        songClicked.removeChild("album");
                        songClicked.removeChild("url");
                        songClicked.addContent(new Element("name").setText(songName.getText()));
                        songClicked.addContent(new Element("artist").setText(songArtist.getText()));
                        songClicked.addContent(new Element("album").setText(songAlbum.getText()));
                        songClicked.addContent(new Element("url").setText(songLocation.getText()));
                        dialog.setVisible(false);

                        try {
                            Content.getInstance().showPlaylist("Library");
                        } catch (Exception ex) {
                        }

                        Library.saveAll();
                    }
                });

                dialog.add(editPanel);
                dialog.pack();
                dialog.setVisible(true);
                dialog.setTitle("Edit Song");
            }
        });

        JMenuItem item2 = new JMenuItem("Delete Track");
        item2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                if (playlist.getSelectedRow() == -1) {
                    return;
                }

                int choice = JOptionPane.showConfirmDialog(null, "Delete track from library?", "Confirm",
                        JOptionPane.YES_NO_OPTION);

                if (choice == JOptionPane.YES_OPTION) {
                    Library.getLib().remove(playlist.getSelectedRow());

                    try {
                        Content.getInstance().showPlaylist("Library");
                    } catch (Exception ex) {
                    }

                    Library.saveAll();
                }
            }
        });

        JMenuItem item3 = new JMenuItem("Add to Playlist...");
        item3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                if (playlist.getSelectedRow() == -1) {
                    return;
                }

                JPanel lists = new JPanel();
                lists.setLayout(new BoxLayout(lists, BoxLayout.PAGE_AXIS));

                Frame parentFrame = (Frame) SwingUtilities.windowForComponent(playlist);
                listsDialog = new JDialog(parentFrame);

                DefaultListModel<String> newModel = new DefaultListModel<String>();
                allLists = new JList<String>(newModel);
                allLists.setSize(new Dimension(150, 500));

                for (int i = 0; i < Library.getList().size(); i++) {
                    String curPlaylistName = ((Element) Library.getList().get(i)).getAttributeValue("id");
                    newModel.addElement(curPlaylistName);
                }

                JButton addOK = new JButton("Add");
                lists.add(new JLabel("Add to which playlist?"));
                lists.add(allLists);
                lists.add(addOK);
                listsDialog.setTitle("Add song to playlist...");
                listsDialog.add(lists);
                listsDialog.pack();
                listsDialog.setVisible(true);

                addOK.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evvent) {
                        if (allLists.getSelectedIndex() != -1) {
                            String selectedId = ((Element) Library.getLib().get(playlist.getSelectedRow()))
                                    .getAttributeValue("id");
                            Element selectedPlaylist = (Element) (Library.getList()
                                    .get(allLists.getSelectedIndex()));
                            selectedPlaylist.addContent(new Element("entry").setText(selectedId));
                            listsDialog.setVisible(false);
                        }
                    }
                });
            }
        });

        menu.add(item1);
        menu.add(item2);
        menu.add(item3);
        playlist.setComponentPopupMenu(menu);
    } else {
        playlist.setComponentPopupMenu(null);

        menu = new JPopupMenu();

        JMenuItem item = new JMenuItem("Remove from playlist");
        menu.add(item);

        item.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent evt) {
                int row = playlist.getSelectedRow();
                if (row == -1) {
                    return;
                }

                for (int i = 0; i < Library.getList().size(); i++) {
                    String curPlaylistName = ((Element) Library.getList().get(i)).getAttributeValue("id");
                    if (currentPlaylist.equals(curPlaylistName)) {
                        ((Element) Library.getList().get(i)).getChildren().remove(row);
                    }
                }

                try {
                    Content.getInstance().showPlaylist(currentPlaylist);
                } catch (Exception ex) {
                }

                Library.saveAll();
            }
        });

        playlist.setComponentPopupMenu(menu);

    }
}

From source file:ac.simons.syndication.modules.atom.AtomModuleGenerator.java

License:BSD License

private void addLinks(final Element parent, final AtomContent content) {
    for (final Link link : content.getLinks()) {
        final Element e = new Element("link", ATOM_NS);

        if (!isBlank(link.getRel())) {
            e.setAttribute(new Attribute("rel", link.getRel()));
        }// ww w  .  j  a  v  a 2  s.  co  m
        if (!isBlank(link.getType())) {
            e.setAttribute(new Attribute("type", link.getType()));
        }
        if (!isBlank(link.getHref())) {
            e.setAttribute(new Attribute("href", link.getHref()));
        }
        if (!isBlank(link.getHreflang())) {
            e.setAttribute(new Attribute("hreflang", link.getHreflang()));
        }
        if (!isBlank(link.getTitle())) {
            e.setAttribute(new Attribute("title", link.getTitle()));
        }
        if (link.getLength() != 0) {
            e.setAttribute(new Attribute("length", Long.toString(link.getLength())));
        }
        parent.addContent(e);
    }
}

From source file:ac.simons.syndication.utils.SyndicationContent.java

License:BSD License

public Element toElement() {
    final Element element = new Element("encoded",
            Namespace.getNamespace("content", "http://purl.org/rss/1.0/modules/content/"));
    element.addContent(new CDATA(content.getValue()));
    return element;
}

From source file:ac.simons.syndication.utils.SyndicationDescription.java

License:BSD License

public Element toElement() {
    final Element element = new Element("description");
    element.addContent(new CDATA(description.getValue()));
    return element;
}

From source file:app.simulation.Exporter.java

License:MIT License

public void exportXML() throws Exception {
    Element root = new Element("simulation");
    Document document = new Document(root);

    if (configuration != null) {
        Element tagConfiguration = new Element("configuration");

        Element delay = new Element("delay");
        delay.setText(String.format("%s", configuration.getDelay()));

        Element iterations = new Element("iterations");
        iterations.setText(String.format("%s", configuration.getIterations()));

        Element agents = new Element("agents");
        agents.setText(String.format("%s", configuration.getAgents()));

        Element latticeSize = new Element("latticeSize");
        latticeSize.setText(String.format("%s", configuration.getLatticeSize()));

        Element description = new Element("description");
        description.setText(String.format("%s", configuration.getDescription()));

        tagConfiguration.addContent(delay);
        tagConfiguration.addContent(iterations);
        tagConfiguration.addContent(agents);
        tagConfiguration.addContent(latticeSize);
        tagConfiguration.addContent(description);

        root.addContent(tagConfiguration);
    }/*from w w w.j a  v  a 2s. c  o  m*/

    if (initialCell != null) {
        Element tagInitialCell = new Element("initialCell");

        Element x = new Element("x");
        x.setText(String.format("%s", initialCell.getX()));

        Element y = new Element("y");
        y.setText(String.format("%s", initialCell.getY()));

        Element z = new Element("z");
        z.setText(String.format("%s", initialCell.getZ()));

        Element state = new Element("state");
        state.setText(String.format("%s", initialCell.getState()));

        Element color = new Element("color");

        Element r = new Element("r");
        r.setText(String.format("%s", initialCell.getColor().getRed()));

        Element g = new Element("g");
        g.setText(String.format("%s", initialCell.getColor().getGreen()));

        Element b = new Element("b");
        b.setText(String.format("%s", initialCell.getColor().getBlue()));

        color.addContent(r);
        color.addContent(g);
        color.addContent(b);

        tagInitialCell.addContent(x);
        tagInitialCell.addContent(y);
        tagInitialCell.addContent(z);
        tagInitialCell.addContent(state);
        tagInitialCell.addContent(color);

        root.addContent(tagInitialCell);
    }

    if (rules != null) {
        Element tagRules = new Element("rules");

        for (Rule rule : rules) {
            Element tagRule = new Element("rule");

            Element neighbourhood = new Element("neighbourhood");
            neighbourhood.setText(rule.getNeighbourhood());

            Element state = new Element("state");
            state.setText(String.format("%s", rule.getState()));

            Element color = new Element("color");

            Element r = new Element("r");
            r.setText(String.format("%s", rule.getColor().getRed()));

            Element g = new Element("g");
            g.setText(String.format("%s", rule.getColor().getGreen()));

            Element b = new Element("b");
            b.setText(String.format("%s", rule.getColor().getBlue()));

            color.addContent(r);
            color.addContent(g);
            color.addContent(b);

            tagRule.addContent(neighbourhood);
            tagRule.addContent(state);
            tagRule.addContent(color);

            tagRules.addContent(tagRule);
        }

        root.addContent(tagRules);
    }

    XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
    outputter.output(document, new FileWriter(path));
}

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 {/* w ww.  java2 s. com*/
            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";
}

From source file:arquivo.ArquivoFilme.java

public String add(String nome, String faixa, String tipo) {
    if (0 != busca(nome, true, "filme").size())
        return "erro nome ja cadastrado";
    SAXBuilder builder = new SAXBuilder();
    try {/*from w  w w  .  ja  v  a2s  .co m*/
        Document doc = builder.build(arquivo);
        Element root = (Element) doc.getRootElement();

        Element filmeE = new Element("filme");

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

        Attribute tipoE = new Attribute("tipo", tipo);
        filmeE.setAttribute(tipoE);

        Attribute faixaE = new Attribute("faixa", faixa);
        filmeE.setAttribute(faixaE);

        root.addContent(filmeE);

        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) {
        e.printStackTrace();
    }
    return "erro cadastral";
}