List of usage examples for javax.xml.transform OutputKeys ENCODING
String ENCODING
To view the source code for javax.xml.transform OutputKeys ENCODING.
Click Source Link
From source file:channellistmaker.channelfilemaker.ChannelDocumentMaker.java
/** * @return ????X???ML????????/*from w ww. j a v a 2 s. com*/ */ public String getChannelList() { try { final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); final DocumentBuilder db = dbf.newDocumentBuilder(); final Document document = db.newDocument(); // >>>>> DOM?? Element channels_e = document.createElement("channels");//<-root document.appendChild(channels_e); final Set<MultiKey<Integer>> keys = this.channels.keySet(); for (MultiKey<Integer> key : keys) { Channel ch = channels.get(key); this.addChannelElement(document, channels_e, ch); } TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); StringWriter writer = new StringWriter();// <-?????????? StreamResult result = new StreamResult(writer); DOMSource source = new DOMSource(document); transformer.transform(source, result); return writer.toString(); } catch (ParserConfigurationException | TransformerConfigurationException ex) { LOG.fatal(ex); return ""; } catch (TransformerException ex) { LOG.fatal(ex); return ""; } }
From source file:net.mumie.cocoon.msg.AbstractPostMessage.java
/** * Returns the XML code of a {@link XMLizable XMLizable} object as a string. *///from w w w. ja va2 s.co m protected String getXMLCode(XMLizable xmlizable) throws ProcessingException { Properties outputProperties = new Properties(); outputProperties.setProperty(OutputKeys.ENCODING, "ASCII"); return XMLUtils.serialize(xmlizable, outputProperties); }
From source file:de.uzk.hki.da.metadata.MetadataStructure.java
public void toEDM(HashMap<String, HashMap<String, List<String>>> indexInfo, File file, PreservationSystem preservationSystem, String objectID, String urn) { try {/*w w w. j ava 2 s. co m*/ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document edmDoc = docBuilder.newDocument(); Element rootElement = edmDoc.createElement("rdf:RDF"); edmDoc.appendChild(rootElement); addXmlNsToEDM(edmDoc, rootElement); for (String id : indexInfo.keySet()) { logger.debug("Index information about " + id + ": " + indexInfo.get(id)); Element providedCHO = addEdmProvidedCHOtoEdm(preservationSystem, id, edmDoc, rootElement); Element aggregation = addOreAggregationToEdm(preservationSystem, id, edmDoc, rootElement); if (indexInfo.get(id).get(C.EDM_IS_PART_OF) == null) { List<String> root = new ArrayList<String>(); root.add("is root element"); indexInfo.get(id).put(C.EDM_HAS_TYPE, root); } if (indexInfo.get(id).get(C.EDM_IDENTIFIER) == null) { List<String> IDs = new ArrayList<String>(); IDs.add(objectID); IDs.add(urn); indexInfo.get(id).put(C.EDM_IDENTIFIER, IDs); } else { indexInfo.get(id).get(C.EDM_IDENTIFIER).add(objectID); indexInfo.get(id).get(C.EDM_IDENTIFIER).add(urn); } for (String elementName : indexInfo.get(id).keySet()) { Element parentNode = null; if (elementName.startsWith("dc:") || elementName.startsWith("dcterms:") || elementName.equals(C.EDM_HAS_TYPE)) { parentNode = providedCHO; } else if (elementName.startsWith("edm:")) { parentNode = aggregation; } if (parentNode != null) { List<String> values = indexInfo.get(id).get(elementName); for (String currentValue : values) { if (!currentValue.equals("")) { addNewElementToParent(preservationSystem, id, elementName, currentValue, parentNode, edmDoc); } } } } } javax.xml.transform.Source source = new javax.xml.transform.dom.DOMSource(edmDoc); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); Result result = new javax.xml.transform.stream.StreamResult(file); transformer.transform(source, result); } catch (Exception e) { logger.error("Unable to create the edm file!"); throw new RuntimeException(e); } }
From source file:de.qucosa.webapi.v1.DocumentResource.java
@Autowired public DocumentResource(FedoraRepository fedoraRepository, URNConfiguration urnConfiguration, FileHandlingService fileHandlingService) throws ParserConfigurationException, TransformerConfigurationException { this.fedoraRepository = fedoraRepository; this.urnConfiguration = urnConfiguration; this.fileHandlingService = fileHandlingService; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); documentBuilder = documentBuilderFactory.newDocumentBuilder(); transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); xmlOutputFactory = XMLOutputFactory.newFactory(); }
From source file:ac.uk.diamond.sample.HttpClientTest.Utils.java
static String xmlToString(Element doc) { StringWriter sw = new StringWriter(); try {//w w w . j ava2 s. co m TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.transform(new DOMSource(doc), new StreamResult(sw)); return sw.toString(); } catch (TransformerException e) { LOG.error("Unable to print message contents: ", e); return "<ERROR: " + e.getMessage() + ">"; } }
From source file:dk.statsbiblioteket.util.xml.DOM.java
/** * Convert the given DOM to an UTF-8 XML String. * * @param dom the Document to convert. * @param withXmlDeclaration if trye, an XML-declaration is prepended. * @return the dom as an XML String./*from w w w . j a v a2 s. c om*/ * @throws TransformerException if the dom could not be converted. */ // TODO: Consider optimizing this with ThreadLocal Transformers public static String domToString(Node dom, boolean withXmlDeclaration) throws TransformerException { Transformer t = TransformerFactory.newInstance().newTransformer(); t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); if (withXmlDeclaration) { t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); } else { t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); } t.setOutputProperty(OutputKeys.METHOD, "xml"); /* Transformer */ StringWriter sw = new StringWriter(); t.transform(new DOMSource(dom), new StreamResult(sw)); return sw.toString(); }
From source file:com.c4om.utils.xmlutils.JavaXMLUtils.java
/** * Method that prints a W3C {@link Document} object to a provided {@link OutputStream}. * Encoding should be correctly specified. * @param document the document to convert * @param os the output stream to print to * @param indent whether lines must be indented or not * @param omitDeclaration whether the XML declaration should be omitted or not. * @param encoding the encoding placed at the XML declaration and used to encode the file. * @return the {@link String} representation of the document * @throws TransformerException if there are problems during the conversion *//*from w w w.ja v a2s . c om*/ public static void printW3CDocumentToOutputStream(Document document, OutputStream os, boolean indent, boolean omitDeclaration, String encoding) throws TransformerException { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omitDeclaration ? "yes" : "no"); transformer.setOutputProperty(OutputKeys.INDENT, indent ? "yes" : "no"); XmlStreamWriter writer; if (encoding != null) { transformer.setOutputProperty(OutputKeys.ENCODING, encoding); writer = new XmlStreamWriter(os, encoding); } else { writer = new XmlStreamWriter(os); } StreamResult streamResult = new StreamResult(writer); transformer.transform(new DOMSource(document), streamResult); }
From source file:ca.nines.ise.util.XMLDriver.java
/** * Serialize an Element into a string containing XML. * * @param element//from w w w. java 2 s.com * @return String * @throws TransformerConfigurationException * @throws TransformerException * @throws UnsupportedEncodingException */ public String serialize(Element element) throws TransformerConfigurationException, TransformerException, UnsupportedEncodingException { ByteArrayOutputStream out = new ByteArrayOutputStream(); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "no"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); DOMSource source = new DOMSource(element); StreamResult stream = new StreamResult(out); transformer.transform(source, stream); return new String(out.toByteArray(), "UTF-8"); }
From source file:com.meltmedia.rodimus.RodimusCli.java
public static void transformDocument(File inputFile, File outputDir, boolean verbose) throws Exception { StreamSource xhtmlHandlerSource = createStreamSource(RodimusCli.class.getResource("/rodimus.xsl")); File indexFile = new File(outputDir, "index.html"); File assetDir = new File(outputDir, IMAGE_DIR_NAME); assetDir.mkdirs();/*from w w w .j a va 2s . c o m*/ // Set up the output buffer. StringBuilderWriter output = new StringBuilderWriter(); // Set up the serializer. ToXMLStream serializer = new ToXMLStream(); serializer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, String.valueOf(2)); serializer.setOutputProperty(OutputPropertiesFactory.S_KEY_LINE_SEPARATOR, "\n"); serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty(OutputPropertiesFactory.S_KEY_ENTITIES, "yes"); serializer.setOutputProperty(OutputKeys.ENCODING, "US-ASCII"); serializer.setWriter(output); // Set up the xhtmlStructure handler. TransformerHandler xhtmlHandler = getContentHandler(xhtmlHandlerSource); xhtmlHandler.setResult(new SAXResult(serializer)); // build the Tika handler. ParseContext context = createParseContext(assetDir, verbose); PostTikaHandler cleanUp = new PostTikaHandler(IMAGE_DIR_NAME); cleanUp.setContentHandler(xhtmlHandler); parseInput(createInputStream(inputFile), cleanUp, context, verbose); // Do some regular expression cleanup. String preOutput = output.toString(); preOutput = preOutput.replaceAll("/>", " />"); // TODO: img is in this list, but it is not a block level element. String blockLevel = "(?:address|article|aside|audio|blockquote|canvas|dd|div|dl|fieldset|figcaption|figure|footer|form|h[1-6]|header|hgroup|hr|noscript|ol|output|p|pre|sectop|table|tfoot|ul|video|img)"; preOutput = preOutput.replaceAll("(</" + blockLevel + ">)(\\s*)(<" + blockLevel + ")", "$1$2$2$3"); preOutput = "<!doctype html>\n" + preOutput; FileUtils.write(indexFile, preOutput, "UTF-8"); // Clean out images dir if it's empty if (assetDir.list().length == 0) { FileUtils.deleteQuietly(assetDir); } }
From source file:Main.java
/** * Writes a DOM document to a stream. The precise output format is not * guaranteed but this method will attempt to indent it sensibly. * * <p class="nonnormative"><b>Important</b>: There might be some problems * with <code><![CDATA[ ]]></code> sections in the DOM tree you pass * into this method. Specifically, some CDATA sections my not be written as * CDATA section or may be merged with other CDATA section at the same * level. Also if plain text nodes are mixed with CDATA sections at the same * level all text is likely to end up in one big CDATA section. * <br>//from ww w .ja v a 2 s.c o m * For nodes that only have one CDATA section this method should work fine. * </p> * * @param doc DOM document to be written * @param out data sink * @param enc XML-defined encoding name (for example, "UTF-8") * @throws IOException if JAXP fails or the stream cannot be written to */ public static void write(Document doc, OutputStream out, String enc) throws IOException { if (enc == null) { throw new NullPointerException( "You must set an encoding; use \"UTF-8\" unless you have a good reason not to!"); // NOI18N } Document doc2 = normalize(doc); ClassLoader orig = Thread.currentThread().getContextClassLoader(); Thread.currentThread() .setContextClassLoader(AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { // #195921 @Override public ClassLoader run() { return new ClassLoader(ClassLoader.getSystemClassLoader().getParent()) { @Override public InputStream getResourceAsStream(String name) { if (name.startsWith("META-INF/services/")) { return new ByteArrayInputStream(new byte[0]); // JAXP #6723276 } return super.getResourceAsStream(name); } }; } })); try { TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(new StreamSource(new StringReader(IDENTITY_XSLT_WITH_INDENT))); DocumentType dt = doc2.getDoctype(); if (dt != null) { String pub = dt.getPublicId(); if (pub != null) { t.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, pub); } String sys = dt.getSystemId(); if (sys != null) { t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, sys); } } t.setOutputProperty(OutputKeys.ENCODING, enc); try { t.setOutputProperty(ORACLE_IS_STANDALONE, "yes"); } catch (IllegalArgumentException x) { // fine, introduced in JDK 7u4 } // See #123816 Set<String> cdataQNames = new HashSet<String>(); collectCDATASections(doc2, cdataQNames); if (cdataQNames.size() > 0) { StringBuilder cdataSections = new StringBuilder(); for (String s : cdataQNames) { cdataSections.append(s).append(' '); //NOI18N } t.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, cdataSections.toString()); } Source source = new DOMSource(doc2); Result result = new StreamResult(out); t.transform(source, result); } catch (javax.xml.transform.TransformerException | RuntimeException e) { // catch anything that happens throw new IOException(e); } finally { Thread.currentThread().setContextClassLoader(orig); } }