Example usage for org.jdom2.output XMLOutputter output

List of usage examples for org.jdom2.output XMLOutputter output

Introduction

In this page you can find the example usage for org.jdom2.output XMLOutputter output.

Prototype

public final void output(EntityRef entity, Writer out) throws IOException 

Source Link

Document

Print out an EntityRef .

Usage

From source file:ResultSetBuilderDemo.java

License:Open Source License

public static void main(String[] args) throws Exception {
    // Tested against Cloudscape database that comes with the J2EE ref impl
    Class.forName("COM.cloudscape.core.JDBCDriver");
    Connection con = DriverManager.getConnection("jdbc:cloudscape:rsbd;create=true");

    // Create and fill commands, needed only on the first run
    Statement prep = con.createStatement();
    prep.executeUpdate(PREP);/*from   ww w  .  j  ava 2 s  . c om*/

    Statement fill = con.createStatement();
    fill.executeUpdate(FILL);

    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery("select id, name, home_url || contact_phone from rsbd");
    ResultSetBuilder builder = new ResultSetBuilder(rs);
    builder.setAsElement(3, "num3");
    //builder.setNamespace(ns);
    //builder.setAsElement("id", "newid");
    //builder.setAsElement("home_url", "newhome_url");
    //builder.setAsElement(4, "some4");
    //builder.setAsAttribute(4, "some4");
    //builder.setAsAttribute("state_flag");
    builder.setAsAttribute("created_time", "ctime");
    Document doc = builder.build();
    XMLOutputter outputter = new XMLOutputter();
    outputter.output(doc, System.out);
}

From source file:Question.java

License:Apache License

/**
 * We use a temporary file between creating the question and sending it to Amazon.  This is
 * probably not the cleanest way to do this, but it gives you a record of the HITs.
 * /*  w ww  .  ja va 2 s  . c o  m*/
 * @throws StoryException
 */
public void writeOutQuestionFile() throws StoryException {
    try {
        logger.debug("writing out the HIT to the file" + tempFile + " ...");
        XMLOutputter xmlOutput = new XMLOutputter();
        xmlOutput.output(doc, new FileOutputStream(tempFile));
    } catch (IOException ioe) {
        throw new StoryException("IO Exception when adding content to question: " + ioe);
    }
}

From source file:sxql.java

License:Open Source License

/**
 * Execute a SQL query and return the result as XML
 * (as a String. But this can be changed to return a DOM/SAX/JDOM tree,
 * to be used, for example, as input to an XSLT processor)
 *//*w w  w.  j  a  v  a  2 s  .co  m*/
public static String query(Connection con, String query, String root, String row, String ns, int maxRows,
        Vector<String> attributes, Vector<String> elements) throws Exception {
    // Execute SQL Query
    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery(query);

    // Create a ResultSetBuilder
    ResultSetBuilder builder = new ResultSetBuilder(rs);

    // Configure some parameters...

    if (root != null) {
        builder.setRootName(root);
    }

    if (row != null) {
        builder.setRowName(row);
    }

    if (ns != null) {
        String namespace = null;
        String url = null;
        int sep = ns.indexOf("/");

        if (sep > 0) {
            namespace = ns.substring(0, sep);
            url = ns.substring(sep + 1);
            builder.setNamespace(Namespace.getNamespace(namespace, url));
        }
    }

    if (maxRows > 0) {
        builder.setMaxRows(maxRows);
    }

    for (int i = 0; i < attributes.size(); i++) {
        String colName = attributes.get(i);
        String attrName = null;

        if (colName.indexOf("/") >= 0) {
            String col = colName;
            int sep = col.indexOf("/");
            colName = col.substring(0, sep);
            attrName = col.substring(sep + 1);
        }

        try { // If it looks like an integer, is the column number
            int colNum = Integer.parseInt(colName);

            if (attrName == null) {
                builder.setAsAttribute(colNum); // attrName = column Name
            } else {
                builder.setAsAttribute(colNum, attrName);
            }
        } catch (NumberFormatException e) {
            // Otherwise it's the column name
            if (attrName == null) {
                builder.setAsAttribute(colName); // attrName = column Name
            } else {
                builder.setAsAttribute(colName, attrName);
            }
        }
    }

    // Rename element
    for (int i = 0; i < elements.size(); i++) {
        String colName = elements.get(i);
        String elemName = null;

        if (colName.indexOf("/") >= 0) {
            String col = colName;
            int sep = col.indexOf("/");
            colName = col.substring(0, sep);
            elemName = col.substring(sep + 1);
        }

        try { // If it looks like an integer, is the column number
            int colNum = Integer.parseInt(colName);

            if (elemName != null) { // It must have an element name
                builder.setAsElement(colNum, elemName);
            }
        } catch (NumberFormatException e) {
            // Otherwise it's the column name
            if (elemName != null) { // It must have an element name
                builder.setAsElement(colName, elemName);
            }
        }
    }

    // Build a JDOM tree
    Document doc = builder.build();

    // Convert the result to XML (as String)
    XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    outputter.output(doc, output);
    return output.toString();
}

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 w  ww  .jav a 2s.  c om
        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:SaveNet.java

License:Apache License

public void WriteFile(Document nnet, String filename) throws JDOMException {

    try {/* w  w w. j  a va 2  s .c  o m*/

        String nnetFileName = filename + ".new.xml";
        XMLOutputter out = new XMLOutputter();
        java.io.FileWriter writer = new java.io.FileWriter(nnetFileName);
        out.output(nnet, writer);
        writer.flush();
        writer.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:AIR.Common.xml.XmlElement.java

License:Open Source License

public String getOuterXml() {
    XMLOutputter outp = new XMLOutputter();
    outp.setFormat(Format.getCompactFormat());
    String returnString = "";
    try (StringWriter sw = new StringWriter()) {
        if (_element instanceof Element)
            outp.output((Element) _element, sw);
        else {/*from www . j a  va 2  s .c  om*/
            // TODO: What to do for other types of Content?
            // Note: Document is not derived from Content.
        }
        returnString = sw.getBuffer().toString();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    return returnString;
}

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);
    }//  w  w  w.  ja  va  2  s.  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.Arquivo.java

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

    try {//  w w w .  j a  v  a  2s . 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 ArquivoF() {
    super(new File("empregados.xml"));
    if (!arquivo.exists()) {
        try {/*w ww. j  a v a2  s.  c  om*/
            Document doc = new Document();
            Element root = new Element("list");
            doc.setRootElement(root);
            XMLOutputter xout = new XMLOutputter();

            xout.output(doc, new FileOutputStream(arquivo));
            System.out.println("Documento criado com sucesso!");

        } catch (Exception e) {
            // TODO: handle exception
        }
    }
}

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 .  jav  a2  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";
}