Example usage for org.jdom2.output Format setEncoding

List of usage examples for org.jdom2.output Format setEncoding

Introduction

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

Prototype

public Format setEncoding(String encoding) 

Source Link

Document

Sets the output encoding.

Usage

From source file:by.epam.lw05.xml.ListToXml.java

private static void documentToXML(Document doc, String path) {

    Format format = Format.getPrettyFormat();
    format.setEncoding("UTF-8");
    XMLOutputter outputter = new XMLOutputter(format);
    try {/*from ww w.  j ava  2  s. co  m*/
        outputter.output(doc, new FileOutputStream(path));
    } catch (FileNotFoundException ex) {
    } catch (IOException ex) {
    }

}

From source file:catalogo.XMLOut.java

public static void criaXML(Document doc) {

    /**//from   w  ww. ja  va2s  .  c  o 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: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) {/* w  ww .j a v a  2 s.  co  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;/*  w  w w.j  ava 2s.c  o 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();
    }
}

From source file:com.medvision360.medrecord.basex.AbstractXmlConverter.java

License:Creative Commons License

protected void outputDocument(Document d, OutputStream os, String encoding) throws IOException {
    Format format = Format.getPrettyFormat();
    format.setTextMode(Format.TextMode.PRESERVE); // this is the default, set just to be very safe
    format.setEncoding(encoding);
    XMLOutputter output = new XMLOutputter(format);
    output.output(d, os);//from   w w w  .j  a  va  2s  .  c om
}

From source file:com.medvision360.medrecord.basex.MockLocatableSerializer.java

License:Creative Commons License

@Override
public void serialize(Locatable locatable, OutputStream os, String encoding) throws IOException {
    String rmEntity = locatable.getArchetypeDetails().getArchetypeId().rmEntity();
    Element root = new Element(rmEntity);
    root.setAttribute("archetype_node_id", locatable.getArchetypeNodeId());

    set(root, "/uid/value", locatable.getUid().getValue());
    set(root, "/archetype_id/value", locatable.getArchetypeDetails().getArchetypeId().getValue());
    set(root, "/name/value", locatable.getName().getValue());

    Document d = new Document(root);

    Format format = Format.getPrettyFormat();
    format.setEncoding(encoding);
    XMLOutputter output = new XMLOutputter(format);
    output.output(d, os);//from  w  w  w  . j a va  2 s  .c om
}

From source file:com.rometools.rome.io.WireFeedOutput.java

License:Open Source License

/**
 * Creates a String with the XML representation for the given WireFeed.
 * <p>/*from  www .ja v a 2  s .c o m*/
 * If the feed encoding is not NULL, it will be used in the XML prolog encoding attribute. It is
 * the responsibility of the developer to ensure that if the String is written to a character
 * stream the stream charset is the same as the feed encoding property.
 * <p>
 * NOTE: This method delages to the 'Document WireFeedOutput#outputJDom(WireFeed)'.
 * <p>
 *
 * @param feed Abstract feed to create XML representation from. The type of the WireFeed must
 *            match the type given to the FeedOuptut constructor.
 * @param prettyPrint pretty-print XML (true) oder collapsed
 * @return a String with the XML representation for the given WireFeed.
 * @throws IllegalArgumentException thrown if the feed type of the WireFeedOutput and WireFeed
 *             don't match.
 * @throws FeedException thrown if the XML representation for the feed could not be created.
 *
 */
public String outputString(final WireFeed feed, final boolean prettyPrint)
        throws IllegalArgumentException, FeedException {
    final Document doc = outputJDom(feed);
    final String encoding = feed.getEncoding();
    Format format;
    if (prettyPrint) {
        format = Format.getPrettyFormat();
    } else {
        format = Format.getCompactFormat();
    }
    if (encoding != null) {
        format.setEncoding(encoding);
    }
    final XMLOutputter outputter = new XMLOutputter(format);
    return outputter.outputString(doc);
}

From source file:com.rometools.rome.io.WireFeedOutput.java

License:Open Source License

/**
 * Writes to an Writer the XML representation for the given WireFeed.
 * <p>/*from w ww .  j a  va 2  s  . c  o m*/
 * If the feed encoding is not NULL, it will be used in the XML prolog encoding attribute. It is
 * the responsibility of the developer to ensure the Writer instance is using the same charset
 * encoding.
 * <p>
 * NOTE: This method delages to the 'Document WireFeedOutput#outputJDom(WireFeed)'.
 * <p>
 *
 * @param feed Abstract feed to create XML representation from. The type of the WireFeed must
 *            match the type given to the FeedOuptut constructor.
 * @param writer Writer to write the XML representation for the given WireFeed.
 * @param prettyPrint pretty-print XML (true) oder collapsed
 * @throws IllegalArgumentException thrown if the feed type of the WireFeedOutput and WireFeed
 *             don't match.
 * @throws IOException thrown if there was some problem writing to the Writer.
 * @throws FeedException thrown if the XML representation for the feed could not be created.
 *
 */
public void output(final WireFeed feed, final Writer writer, final boolean prettyPrint)
        throws IllegalArgumentException, IOException, FeedException {
    final Document doc = outputJDom(feed);
    final String encoding = feed.getEncoding();
    Format format;
    if (prettyPrint) {
        format = Format.getPrettyFormat();
    } else {
        format = Format.getCompactFormat();
    }
    if (encoding != null) {
        format.setEncoding(encoding);
    }
    final XMLOutputter outputter = new XMLOutputter(format);
    outputter.output(doc, writer);
}

From source file:com.sun.syndication.io.WireFeedOutput.java

License:Open Source License

/**
 * Creates a String with the XML representation for the given WireFeed.
 * <p>//from w  ww .j av a 2s. co m
 * If the feed encoding is not NULL, it will be used in the XML prolog encoding attribute. It is the responsibility
 * of the developer to ensure that if the String is written to a character stream the stream charset is the same as
 * the feed encoding property.
 * <p>
 * NOTE: This method delages to the 'Document WireFeedOutput#outputJDom(WireFeed)'.
 * <p>
 * @param feed Abstract feed to create XML representation from. The type of the WireFeed must match
 *        the type given to the FeedOuptut constructor.
 * @param prettyPrint pretty-print XML (true) oder collapsed
 * @return a String with the XML representation for the given WireFeed.
 * @throws IllegalArgumentException thrown if the feed type of the WireFeedOutput and WireFeed don't match.
 * @throws FeedException thrown if the XML representation for the feed could not be created.
 *
 */
public String outputString(WireFeed feed, boolean prettyPrint) throws IllegalArgumentException, FeedException {
    Document doc = outputJDom(feed);
    String encoding = feed.getEncoding();
    Format format = prettyPrint ? Format.getPrettyFormat() : Format.getCompactFormat();
    if (encoding != null) {
        format.setEncoding(encoding);
    }
    XMLOutputter outputter = new XMLOutputter(format);
    return outputter.outputString(doc);
}

From source file:com.sun.syndication.io.WireFeedOutput.java

License:Open Source License

/**
 * Writes to an Writer the XML representation for the given WireFeed.
 * <p>/*  w ww . j  a va  2  s .c o m*/
 * If the feed encoding is not NULL, it will be used in the XML prolog encoding attribute. It is the responsibility
 * of the developer to ensure the Writer instance is using the same charset encoding.
 * <p>
 * NOTE: This method delages to the 'Document WireFeedOutput#outputJDom(WireFeed)'.
 * <p>
 * @param feed Abstract feed to create XML representation from. The type of the WireFeed must match
 *        the type given to the FeedOuptut constructor.
 * @param writer Writer to write the XML representation for the given WireFeed.
 * @param prettyPrint pretty-print XML (true) oder collapsed
 * @throws IllegalArgumentException thrown if the feed type of the WireFeedOutput and WireFeed don't match.
 * @throws IOException thrown if there was some problem writing to the Writer.
 * @throws FeedException thrown if the XML representation for the feed could not be created.
 *
 */
public void output(WireFeed feed, Writer writer, boolean prettyPrint)
        throws IllegalArgumentException, IOException, FeedException {
    Document doc = outputJDom(feed);
    String encoding = feed.getEncoding();
    Format format = prettyPrint ? Format.getPrettyFormat() : Format.getCompactFormat();
    if (encoding != null) {
        format.setEncoding(encoding);
    }
    XMLOutputter outputter = new XMLOutputter(format);
    outputter.output(doc, writer);
}