Example usage for org.jdom2.output XMLOutputter XMLOutputter

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

Introduction

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

Prototype

public XMLOutputter() 

Source Link

Document

This will create an XMLOutputter with a default Format and XMLOutputProcessor .

Usage

From source file:catalogo.XMLOut.java

public static void criaXML(Document doc) {

    /**/*  ww  w.ja  va 2s. co m*/
     * Esta funo recebe como parmetro um objeto Document corretamente estruturado
     * e cria um arquivo .XML com nome fornecido pelo usurio.
     */

    Scanner in = new Scanner(System.in);

    //Mgica que cria o arquivo
    XMLOutputter xmlOutput = new XMLOutputter();
    Format format = Format.getPrettyFormat();
    format.setEncoding("ISO-8859-1");
    xmlOutput.setFormat(format);

    System.out.printf("Informe o nome do arquivo .xml a ser criado: \n" + "(exemplo: listagem.xml)\n>>> ");
    String name = in.nextLine();

    try {
        xmlOutput.output(doc, new FileWriter("outputs/".concat(name)));
        System.out.println("Arquivo de listagem criado.");
    } catch (Exception e) {
        System.out.println("Falha ao criar arquivo.");
    }
}

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);/*  w w w  . j  a v a  2  s  .  c  o  m*/
    xmlOutput.output(doc, writer);
    writer.flush();
    writer.close();
}

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 .jav a2 s .c  om
    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   w  w w  . ja v  a  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 boolean removeUser(User u) {
    File file = new File("Sistema.xml");
    Document newDocument = null;//from  ww w  .  j  a v a  2 s  . 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;
}

From source file:com.astronomy.project.Project.java

/**
 * Save project as XML file/*from  w w  w.  j a v  a  2s .co  m*/
 * @param file XML file
 * @throws FileNotFoundException File not found error
 * @throws IOException IO error
 * @throws NullPointerException Null pointer error 
 */
public void toXML(File file) throws FileNotFoundException, IOException, NullPointerException {
    Element estudioElemento = new Element("estudio");
    Document doc = new Document(estudioElemento);
    estudioElemento.setAttribute("nombre", name);
    Element aa = new Element("alineamientos");
    estudioElemento.addContent(aa);
    for (int i = 0; i < data.size(); i++) {
        Alignment ali = (Alignment) data.get(i);
        aa.addContent(ali.getXMLElement());
    }

    XMLOutputter xmlOutput = new XMLOutputter();
    xmlOutput.setFormat(Format.getPrettyFormat());
    FileOutputStream out = null;
    try {
        xmlOutput.output(doc, out = new FileOutputStream(file));
    } finally {
        out.close();
    }
}

From source file:com.bc.ceres.nbmgen.NbmGenTool.java

License:Open Source License

private static void writeXml(File file, Document document) throws IOException {
    XMLOutputter xmlOutput = new XMLOutputter();
    Format format = Format.getPrettyFormat();
    format.setIndent("    ");
    xmlOutput.setFormat(format);/*from  w w  w. ja  v a 2  s  .  c o m*/
    xmlOutput.output(document, new FileWriter(file));
}

From source file:com.compomics.pladipus.core.control.updates.ProcessingBeanUpdater.java

/**
 * Adds a new class to the bean definition
 * @param fullyDefinedClassName the fully defined class name
 * @throws IllegalArgumentException//w  w  w .j  av a2 s  . c o m
 * @throws IOException
 * @throws JDOMException
 */
public void addNewProcessingStep(String fullyDefinedClassName)
        throws IllegalArgumentException, IOException, JDOMException {
    String className = fullyDefinedClassName.substring(fullyDefinedClassName.lastIndexOf(".") + 1);

    SAXBuilder builder = new SAXBuilder();
    Document document = builder.build(beanXMLDefinitionFile);

    //check if the class is not already in there
    for (Element aBean : document.getRootElement().getChildren()) {
        if (aBean.getAttribute("class").getValue().equals(fullyDefinedClassName)) {
            throw new IllegalArgumentException(
                    "Class is already defined in the bean configuration for " + aBean.getAttributeValue("id"));
        } else if (aBean.getAttribute("id").getValue().equals(className)) {
            throw new IllegalArgumentException("Classname is already in use");
        }
    }

    Element newClassElement = new Element("bean").setAttribute("id", className)
            .setAttribute("class", fullyDefinedClassName).setAttribute("lazy-init", "true");
    document.getRootElement().addContent(newClassElement);
    XMLOutputter outputter = new XMLOutputter();
    try (StringWriter stringWriter = new StringWriter();
            FileWriter writer = new FileWriter(beanXMLDefinitionFile);) {
        outputter.output(document, stringWriter);
        String output = stringWriter.getBuffer().toString();
        //remove empty namespaces
        output = output.replace(" xmlns=\"\"", "");
        writer.append(output);
    }
}

From source file:com.dexterapps.android.translator.TranslateAndSaveAndroid.java

License:Apache License

private void generateXMLForCountry(String countryCode, List<String> translatedText,
        ArrayList<AndroidStringMapping> stringXmlDOM, HashMap<String, Integer> baseStringResourcesMapping,
        String outPutFolder) {/*from ww  w. j a v  a 2 s  .  c  o m*/
    Element resources = new Element("resources");
    Document doc = new Document(resources);

    //System.out.println("Generating XML");

    //int totalNumberOfStrings = 0;
    for (int i = 0; i < stringXmlDOM.size(); i++) {
        AndroidStringMapping stringMapping = stringXmlDOM.get(i);

        if (stringMapping.getType().equalsIgnoreCase("string")) {
            Element string = new Element("string");
            string.setAttribute(new Attribute("name", stringMapping.getAttributeName()));

            //To get the attribute value, use the hasmap and then string array
            int translatedTextIndex = baseStringResourcesMapping.get(stringMapping.getAttributeValue());
            string.setText(translatedText.get(translatedTextIndex));

            //Add element to root
            doc.getRootElement().addContent(string);
        } else if (stringMapping.getType().equalsIgnoreCase("string-array")) {
            Element stringArray = new Element("string-array");
            stringArray.setAttribute(new Attribute("name", stringMapping.getAttributeName()));

            //Since this is String array it will have a list of string items, get the list of string items

            ArrayList<String> stringArrayItems = (ArrayList<String>) stringMapping.getAttributeValue();

            for (int j = 0; j < stringArrayItems.size(); j++) {
                int translatedTextIndex = baseStringResourcesMapping.get(stringArrayItems.get(j));
                stringArray.addContent(new Element("item").setText(translatedText.get(translatedTextIndex)));
            }

            //Add element to root
            doc.getRootElement().addContent(stringArray);
        } else {
            Element stringArray = new Element("plurals");
            stringArray.setAttribute(new Attribute("name", stringMapping.getAttributeName()));

            //Since this is plurals it will have a list of string items with values, get the list of string items

            ArrayList<AndroidStringPlurals> stringPluralItems = (ArrayList<AndroidStringPlurals>) stringMapping
                    .getAttributeValue();

            for (int j = 0; j < stringPluralItems.size(); j++) {

                int translatedTextIndex = baseStringResourcesMapping
                        .get(stringPluralItems.get(j).getAttributeValue());
                Element pluralItem = new Element("item");
                pluralItem.setAttribute("quantity", stringPluralItems.get(j).getAttributeName());
                pluralItem.setText(translatedText.get(translatedTextIndex));

                stringArray.addContent(pluralItem);
            }

            //Add element to root
            doc.getRootElement().addContent(stringArray);
        }
    }

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

    try {
        // System.out.println("Saving File");
        Format format = Format.getPrettyFormat();
        format.setEncoding("UTF-8");
        xmlOutput.setFormat(format);

        File file = new File(outPutFolder + "/values-" + countryCode);
        if (!file.exists()) {
            file.mkdir();
        }

        file = new File(outPutFolder + "/values-" + countryCode + "/strings.xml");
        FileOutputStream fop = new FileOutputStream(file);
        xmlOutput.output(doc, fop);
        System.out.println("Translation Successful !!");

        // System.out.println("File Saved!");
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:com.globalsight.dispatcher.bo.JobTask.java

License:Apache License

private void createTargetFile(JobBO p_job, String[] p_targetSegments) throws IOException {
    OutputStream writer = null;//from   w  ww .  j a  v a  2  s. co m
    File fileStorage = CommonDAO.getFileStorage();
    File srcFile = p_job.getSrcFile();
    Account account = DispatcherDAOFactory.getAccountDAO().getAccount(p_job.getAccountId());
    File trgDir = CommonDAO.getFolder(fileStorage, account.getAccountName() + File.separator + p_job.getJobID()
            + File.separator + AppConstants.XLF_TARGET_FOLDER);
    File trgFile = new File(trgDir, srcFile.getName());
    FileUtils.copyFile(srcFile, trgFile);
    String encoding = FileUtil.getEncodingOfXml(trgFile);

    try {
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(p_job.getSrcFile());
        Element root = doc.getRootElement(); // Get root element
        Namespace namespace = root.getNamespace();
        Element fileElem = root.getChild("file", namespace);
        XPathFactory xFactory = XPathFactory.instance();
        XPathExpression<Element> expr = xFactory.compile("//trans-unit", Filters.element(), null, namespace);
        List<Element> tuList = expr.evaluate(fileElem.getChild("body", namespace));
        for (int tuIndex = 0, trgIndex = 0; tuIndex < tuList.size()
                && trgIndex < p_targetSegments.length; tuIndex++, trgIndex++) {
            if (p_targetSegments[trgIndex] == null) {
                continue;
            }

            Element elem = (Element) tuList.get(tuIndex);
            Element srcElem = elem.getChild("source", namespace);
            Element trgElem = elem.getChild("target", namespace);
            if (srcElem == null || srcElem.getContentSize() == 0) {
                trgIndex--;
                continue;
            }

            if (trgElem != null) {
                setTargetSegment(trgElem, p_targetSegments[trgIndex], encoding);
            } else {
                trgElem = new Element("target", namespace);
                setTargetSegment(trgElem, p_targetSegments[trgIndex], encoding);
                elem.addContent(trgElem);
            }

        }

        XMLOutputter xmlOutput = new XMLOutputter();
        Format format = Format.getRawFormat();
        format.setEncoding(encoding);
        writer = new FileOutputStream(trgFile);
        xmlOutput.setFormat(format);
        writeBOM(writer, format.getEncoding());
        xmlOutput.output(doc, writer);
        p_job.setTrgFile(trgFile);
        logger.info("Create Target File: " + trgFile);
    } catch (JDOMException e1) {
        logger.error("CreateTargetFile Error: ", e1);
    } catch (IOException e1) {
        logger.error("CreateTargetFile Error: ", e1);
    } finally {
        if (writer != null)
            writer.close();
    }
}