List of usage examples for javax.xml.stream XMLStreamWriter writeStartDocument
public void writeStartDocument(String encoding, String version) throws XMLStreamException;
From source file:CursorWriter.java
public static void main(String[] args) throws Exception { String fileName = "yourXML.xml"; XMLOutputFactory xof = XMLOutputFactory.newInstance(); XMLStreamWriter xtw = null; xtw = xof.createXMLStreamWriter(new FileWriter(fileName)); xtw.writeComment("all elements here are explicitly in the HTML namespace"); xtw.writeStartDocument("utf-8", "1.0"); xtw.setPrefix("html", "http://www.w3.org/TR/REC-html40"); xtw.writeStartElement("http://www.w3.org/TR/REC-html40", "html"); xtw.writeNamespace("html", "http://www.w3.org/TR/REC-html40"); xtw.writeStartElement("http://www.w3.org/TR/REC-html40", "head"); xtw.writeStartElement("http://www.w3.org/TR/REC-html40", "title"); xtw.writeCharacters("character"); xtw.writeEndElement();// w w w . j a v a2 s . c o m xtw.writeEndElement(); xtw.writeStartElement("http://www.w3.org/TR/REC-html40", "body"); xtw.writeStartElement("http://www.w3.org/TR/REC-html40", "p"); xtw.writeCharacters("another character"); xtw.writeStartElement("http://www.w3.org/TR/REC-html40", "a"); xtw.writeAttribute("href", "http://www.java2s.com"); xtw.writeCharacters("here"); xtw.writeEndElement(); xtw.writeEndElement(); xtw.writeEndElement(); xtw.writeEndElement(); xtw.writeEndDocument(); xtw.flush(); xtw.close(); System.out.println("Done"); }
From source file:Main.java
/** * @param encoding/*from www . j av a2 s. c o m*/ * @param version * @param xmlsw * @throws XMLStreamException */ public static void writeStartDocument(String encoding, String version, XMLStreamWriter xmlsw) throws XMLStreamException { xmlsw.writeStartDocument(encoding, version); }
From source file:Main.java
public static String convertBean2Xml(Object obj) throws IOException { String result = null;/* w w w . j a va 2 s. c om*/ try { JAXBContext context = JAXBContext.newInstance(obj.getClass()); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance(); XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(baos, (String) marshaller.getProperty(Marshaller.JAXB_ENCODING)); xmlStreamWriter.writeStartDocument((String) marshaller.getProperty(Marshaller.JAXB_ENCODING), "1.0"); marshaller.marshal(obj, xmlStreamWriter); xmlStreamWriter.writeEndDocument(); xmlStreamWriter.close(); result = baos.toString("UTF-8"); } catch (JAXBException e) { e.printStackTrace(); return null; } catch (XMLStreamException e) { e.printStackTrace(); return null; } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } return result; }
From source file:eu.interedition.collatex.tools.CollationPipe.java
public static void start(CommandLine commandLine) throws Exception { List<SimpleWitness> witnesses = null; Function<String, Stream<String>> tokenizer = SimplePatternTokenizer.BY_WS_OR_PUNCT; Function<String, String> normalizer = SimpleTokenNormalizers.LC_TRIM_WS; Comparator<Token> comparator = new EqualityTokenComparator(); CollationAlgorithm collationAlgorithm = null; boolean joined = true; final String[] witnessSpecs = commandLine.getArgs(); final InputStream[] inputStreams = new InputStream[witnessSpecs.length]; for (int wc = 0, wl = witnessSpecs.length; wc < wl; wc++) { try {/*from www .j a v a 2 s . c om*/ inputStreams[wc] = argumentToInputStream(witnessSpecs[wc]); } catch (MalformedURLException urlEx) { throw new ParseException("Invalid resource: " + witnessSpecs[wc]); } } if (inputStreams.length < 1) { throw new ParseException("No input resource(s) given"); } else if (inputStreams.length < 2) { try (InputStream inputStream = inputStreams[0]) { final SimpleCollation collation = JsonProcessor.read(inputStream); witnesses = collation.getWitnesses(); collationAlgorithm = collation.getAlgorithm(); joined = collation.isJoined(); } } final String script = commandLine.getOptionValue("s"); try { final PluginScript pluginScript = (script == null ? PluginScript.read("<internal>", new StringReader("")) : PluginScript.read(argumentToInput(script))); tokenizer = Optional.ofNullable(pluginScript.tokenizer()).orElse(tokenizer); normalizer = Optional.ofNullable(pluginScript.normalizer()).orElse(normalizer); comparator = Optional.ofNullable(pluginScript.comparator()).orElse(comparator); } catch (IOException e) { throw new ParseException("Failed to read script '" + script + "' - " + e.getMessage()); } switch (commandLine.getOptionValue("a", "").toLowerCase()) { case "needleman-wunsch": collationAlgorithm = CollationAlgorithmFactory.needlemanWunsch(comparator); break; case "medite": collationAlgorithm = CollationAlgorithmFactory.medite(comparator, SimpleToken.TOKEN_MATCH_EVALUATOR); break; case "gst": collationAlgorithm = CollationAlgorithmFactory.greedyStringTiling(comparator, 2); break; default: collationAlgorithm = Optional.ofNullable(collationAlgorithm) .orElse(CollationAlgorithmFactory.dekker(comparator)); break; } if (witnesses == null) { final Charset inputCharset = Charset .forName(commandLine.getOptionValue("ie", StandardCharsets.UTF_8.name())); final boolean xmlMode = commandLine.hasOption("xml"); final XPathExpression tokenXPath = XPathFactory.newInstance().newXPath() .compile(commandLine.getOptionValue("xp", "//text()")); witnesses = new ArrayList<>(inputStreams.length); for (int wc = 0, wl = inputStreams.length; wc < wl; wc++) { try (InputStream stream = inputStreams[wc]) { final String sigil = "w" + (wc + 1); if (!xmlMode) { final BufferedReader reader = new BufferedReader( new InputStreamReader(stream, inputCharset)); final StringWriter writer = new StringWriter(); final char[] buf = new char[1024]; while (reader.read(buf) != -1) { writer.write(buf); } witnesses.add(new SimpleWitness(sigil, writer.toString(), tokenizer, normalizer)); } else { final DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance() .newDocumentBuilder(); final Document document = documentBuilder.parse(stream); document.normalizeDocument(); final SimpleWitness witness = new SimpleWitness(sigil); final NodeList tokenNodes = (NodeList) tokenXPath.evaluate(document, XPathConstants.NODESET); final List<Token> tokens = new ArrayList<>(tokenNodes.getLength()); for (int nc = 0; nc < tokenNodes.getLength(); nc++) { final String tokenText = tokenNodes.item(nc).getTextContent(); tokens.add(new SimpleToken(witness, tokenText, normalizer.apply(tokenText))); } witness.setTokens(tokens); witnesses.add(witness); } } } } final VariantGraph variantGraph = new VariantGraph(); collationAlgorithm.collate(variantGraph, witnesses); if (joined && !commandLine.hasOption("t")) { VariantGraph.JOIN.apply(variantGraph); } final String output = commandLine.getOptionValue("o", "-"); final Charset outputCharset = Charset .forName(commandLine.getOptionValue("oe", StandardCharsets.UTF_8.name())); final String outputFormat = commandLine.getOptionValue("f", "json").toLowerCase(); try (PrintWriter out = argumentToOutput(output, outputCharset)) { final SimpleVariantGraphSerializer serializer = new SimpleVariantGraphSerializer(variantGraph); if ("csv".equals(outputFormat)) { serializer.toCsv(out); } else if ("dot".equals(outputFormat)) { serializer.toDot(out); } else if ("graphml".equals(outputFormat) || "tei".equals(outputFormat)) { XMLStreamWriter xml = null; try { xml = XMLOutputFactory.newInstance().createXMLStreamWriter(out); xml.writeStartDocument(outputCharset.name(), "1.0"); if ("graphml".equals(outputFormat)) { serializer.toGraphML(xml); } else { serializer.toTEI(xml); } xml.writeEndDocument(); } catch (XMLStreamException e) { throw new IOException(e); } finally { if (xml != null) { try { xml.close(); } catch (XMLStreamException e) { // ignored } } } } else { JsonProcessor.write(variantGraph, out); } } }
From source file:eu.scape_project.planning.xml.ProjectExportAction.java
/** * Dumps binary data to provided file. It results in an XML file with a * single element: data.//from w ww.j a v a2 s .com * * @param id * @param data * @param f * @param encoder * @throws IOException */ private static void writeBinaryData(int id, InputStream data, File f) throws IOException { XMLOutputFactory factory = XMLOutputFactory.newInstance(); try { XMLStreamWriter writer = factory.createXMLStreamWriter(new FileWriter(f)); writer.writeStartDocument(PlanXMLConstants.ENCODING, "1.0"); writer.writeStartElement("data"); writer.writeAttribute("id", "" + id); Base64InputStream base64EncodingIn = new Base64InputStream(data, true, PlanXMLConstants.BASE64_LINE_LENGTH, PlanXMLConstants.BASE64_LINE_BREAK); OutputStream out = new WriterOutputStream(new XMLStreamContentWriter(writer), PlanXMLConstants.ENCODING); // read the binary data and encode it on the fly IOUtils.copy(base64EncodingIn, out); out.flush(); // all data is written - end writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); writer.close(); } catch (XMLStreamException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.microsoft.windowsazure.services.table.client.AtomPubParser.java
/** * Reserved for internal use. Writes a single entity to the specified <code>XMLStreamWriter</code> as a complete XML * document./* w w w . ja v a 2 s .c o m*/ * * @param entity * The instance implementing {@link TableEntity} to write to the output stream. * @param isTableEntry * A flag indicating the entity is a reference to a table at the top level of the storage service when * <code>true<code> and a reference to an entity within a table when <code>false</code>. * @param xmlw * The <code>XMLStreamWriter</code> to write the entity to. * @param opContext * An {@link OperationContext} object used to track the execution of the operation. * * @throws XMLStreamException * if an error occurs creating or accessing the stream. * @throws StorageException * if a Storage service error occurs. */ protected static void writeSingleEntityToStream(final TableEntity entity, final boolean isTableEntry, final XMLStreamWriter xmlw, final OperationContext opContext) throws XMLStreamException, StorageException { // default is UTF8 xmlw.writeStartDocument("UTF-8", "1.0"); writeEntityToStream(entity, isTableEntry, xmlw, opContext); // end doc xmlw.writeEndDocument(); xmlw.flush(); }
From source file:com.rockhoppertech.music.midi.js.xml.ModeFactoryXMLHelper.java
public static void write(List<Scale> modeList, String fileName) { XMLOutputFactory xof = XMLOutputFactory.newInstance(); XMLStreamWriter xtw = null; // <mode> // <name>Peruvian tritonic 2</name> // <interval>3</interval> // <interval>4</interval> // <interval>5</interval> // </mode> String ns = "http://rockhoppertech.com/modes-1.0"; // StringWriter sw = new StringWriter(); try {//from www.j a v a2 s. co m xtw = xof.createXMLStreamWriter(new FileWriter(fileName)); // xtw = xof.createXMLStreamWriter(sw); xtw.writeComment("all elements here are explicitly in the mode namespace"); xtw.writeStartDocument("utf-8", "1.0"); xtw.setPrefix("modes", ns); xtw.writeStartElement(ns, "modes"); xtw.writeNamespace("modes", ns); for (Scale scale : modeList) { // xtw.writeStartElement(ns, "mode"); xtw.writeStartElement("mode"); // xtw.writeStartElement(ns, "name"); xtw.writeStartElement("name"); xtw.writeCharacters(scale.getName()); xtw.writeEndElement(); // xtw.writeStartElement(ns, "intervals"); // xtw.writeStartElement(ns, "interval"); xtw.writeStartElement("intervals"); int[] intervals = scale.getIntervals(); for (int i = 0; i < intervals.length; i++) { xtw.writeStartElement("interval"); xtw.writeCharacters("" + intervals[i]); xtw.writeEndElement(); } xtw.writeEndElement(); // intervals xtw.writeEndElement(); // mode } xtw.writeEndElement(); // modes xtw.writeEndDocument(); xtw.flush(); xtw.close(); // System.err.println(sw.toString()); } catch (XMLStreamException | IOException e) { logger.error(e.getLocalizedMessage(), e); e.printStackTrace(); } }
From source file:Main.java
public final String getMessage() throws Exception { Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty("jaxb.encoding", "ISO-8859-1"); jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(baos, (String) jaxbMarshaller.getProperty(Marshaller.JAXB_ENCODING)); xmlStreamWriter.writeStartDocument((String) jaxbMarshaller.getProperty(Marshaller.JAXB_ENCODING), "1.0"); jaxbMarshaller.marshal(this, xmlStreamWriter); xmlStreamWriter.writeEndDocument();// w w w . j ava 2 s. com xmlStreamWriter.close(); return new String(baos.toByteArray()); }
From source file:de.shadowhunt.subversion.internal.httpv1.CheckoutOperation.java
@Override protected HttpUriRequest createRequest() { final Writer body = new StringBuilderWriter(); try {/* w w w .j a v a 2 s. c o m*/ final XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(body); writer.writeStartDocument(XmlConstants.ENCODING, XmlConstants.VERSION_1_0); writer.writeStartElement("checkout"); writer.writeDefaultNamespace(XmlConstants.DAV_NAMESPACE); writer.writeStartElement("activity-set"); writer.writeStartElement("href"); final URI transactionURI = URIUtils.createURI(repository, transaction); writer.writeCData(transactionURI.toString()); writer.writeEndElement(); // href writer.writeEndElement(); // activity-set writer.writeEmptyElement("apply-to-version"); writer.writeEndElement(); //checkout writer.writeEndDocument(); writer.close(); } catch (final XMLStreamException e) { throw new SubversionException("could not create request body", e); } final URI uri = URIUtils.createURI(repository, resource); final DavTemplateRequest request = new DavTemplateRequest("CHECKOUT", uri); request.setEntity(new StringEntity(body.toString(), CONTENT_TYPE_XML)); return request; }
From source file:de.shadowhunt.subversion.internal.CommitMessageOperation.java
@Override protected HttpUriRequest createRequest() { final Writer body = new StringBuilderWriter(); try {// w w w .j a v a2s . com final XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(body); writer.writeStartDocument(XmlConstants.ENCODING, XmlConstants.VERSION_1_0); writer.writeStartElement("propertyupdate"); writer.writeDefaultNamespace(XmlConstants.DAV_NAMESPACE); writer.writeStartElement("set"); writer.writeStartElement("prop"); writer.setPrefix(XmlConstants.SUBVERSION_DAV_PREFIX, XmlConstants.SUBVERSION_DAV_NAMESPACE); writer.writeStartElement(XmlConstants.SUBVERSION_DAV_NAMESPACE, "log"); writer.writeNamespace(XmlConstants.SUBVERSION_DAV_PREFIX, XmlConstants.SUBVERSION_DAV_NAMESPACE); writer.writeCharacters(message); writer.writeEndElement(); // log writer.writeEndElement(); // prop writer.writeEndElement(); // set writer.writeEndElement(); // propertyupdate writer.writeEndDocument(); writer.close(); } catch (final XMLStreamException e) { throw new SubversionException("could not create request body", e); } final URI uri = URIUtils.createURI(repository, resource); final DavTemplateRequest request = new DavTemplateRequest("PROPPATCH", uri); request.setEntity(new StringEntity(body.toString(), CONTENT_TYPE_XML)); return request; }