Example usage for javax.xml.stream XMLOutputFactory createXMLEventWriter

List of usage examples for javax.xml.stream XMLOutputFactory createXMLEventWriter

Introduction

In this page you can find the example usage for javax.xml.stream XMLOutputFactory createXMLEventWriter.

Prototype

public abstract XMLEventWriter createXMLEventWriter(java.io.Writer stream) throws XMLStreamException;

Source Link

Document

Create a new XMLEventWriter that writes to a writer

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    XMLEventWriter writer = outputFactory.createXMLEventWriter(System.out);
    XMLEventFactory xmlEventFactory = XMLEventFactory.newInstance();

    StartDocument startDocument = xmlEventFactory.createStartDocument("UTF-8", "1.0");
    writer.add(startDocument);/*from  w ww.j  a v  a  2 s  . c  o  m*/

    StartElement startElement = xmlEventFactory.createStartElement("", "", "My-list");
    writer.add(startElement);

    Attribute attribute = xmlEventFactory.createAttribute("version", "1");
    List attributeList = Arrays.asList(attribute);
    List nsList = Arrays.asList();
    StartElement startElement2 = xmlEventFactory.createStartElement("", "", "Item", attributeList.iterator(),
            nsList.iterator());
    writer.add(startElement2);

    StartElement codeSE = xmlEventFactory.createStartElement("", "", "code");
    writer.add(codeSE);
    Characters codeChars = xmlEventFactory.createCharacters("I001");
    writer.add(codeChars);
    EndElement codeEE = xmlEventFactory.createEndElement("", "", "code");
    writer.add(codeEE);

    StartElement nameSE = xmlEventFactory.createStartElement(" ", " ", "name");
    writer.add(nameSE);
    Characters nameChars = xmlEventFactory.createCharacters("a name");
    writer.add(nameChars);
    EndElement nameEE = xmlEventFactory.createEndElement("", "", "name");
    writer.add(nameEE);

    StartElement contactSE = xmlEventFactory.createStartElement("", "", "contact");
    writer.add(contactSE);
    Characters contactChars = xmlEventFactory.createCharacters("another name");
    writer.add(contactChars);
    EndElement contactEE = xmlEventFactory.createEndElement("", "", "contact");
    writer.add(contactEE);

    EndDocument ed = xmlEventFactory.createEndDocument();
    writer.add(ed);

    writer.flush();
    writer.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEventWriter writer = outputFactory.createXMLEventWriter(System.out);

    writer.add(eventFactory.createStartDocument("UTF-8", "1.0"));
    writer.add(eventFactory.createStartElement(new QName("p"), null, null));
    XMLEvent sampleElement = eventFactory.createStartElement("", null, "s", null, null);
    writer.add(sampleElement);/*  w w  w .  j  av  a 2 s . c  o  m*/
    writer.add(eventFactory.createEndElement("", null, "s"));
    writer.add(sampleElement);
    writer.add(eventFactory.createEndDocument());
    writer.flush();
}

From source file:XMLEventWriterDemo.java

public static void main(String[] args) throws Exception {
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();

    XMLEventWriter writer = outputFactory.createXMLEventWriter(System.out);

    XMLEventFactory xmlEventFactory = XMLEventFactory.newInstance();

    StartDocument startDocument = xmlEventFactory.createStartDocument("UTF-8", "1.0");
    writer.add(startDocument);/*from ww w . j a v  a 2s .co  m*/

    StartElement startElement = xmlEventFactory.createStartElement("", "", "My-list");
    writer.add(startElement);

    Attribute attribute = xmlEventFactory.createAttribute("version", "1");
    List attributeList = Arrays.asList(attribute);
    List nsList = Arrays.asList();
    StartElement startElement2 = xmlEventFactory.createStartElement("", "", "Item", attributeList.iterator(),
            nsList.iterator());
    writer.add(startElement2);

    StartElement codeSE = xmlEventFactory.createStartElement("", "", "code");
    writer.add(codeSE);
    Characters codeChars = xmlEventFactory.createCharacters("I001");
    writer.add(codeChars);
    EndElement codeEE = xmlEventFactory.createEndElement("", "", "code");
    writer.add(codeEE);

    StartElement nameSE = xmlEventFactory.createStartElement(" ", " ", "name");
    writer.add(nameSE);
    Characters nameChars = xmlEventFactory.createCharacters("a name");
    writer.add(nameChars);
    EndElement nameEE = xmlEventFactory.createEndElement("", "", "name");
    writer.add(nameEE);

    StartElement contactSE = xmlEventFactory.createStartElement("", "", "contact");
    writer.add(contactSE);
    Characters contactChars = xmlEventFactory.createCharacters("another name");
    writer.add(contactChars);
    EndElement contactEE = xmlEventFactory.createEndElement("", "", "contact");
    writer.add(contactEE);

    EndDocument ed = xmlEventFactory.createEndDocument();
    writer.add(ed);

    writer.flush();
    writer.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    File source = new File(args[0]);
    File target = new File(source + ".new");

    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    InputStream in = new FileInputStream(source);
    XMLEventReader reader = inputFactory.createXMLEventReader(in);

    OutputStream out = new FileOutputStream(target);
    XMLEventWriter writer = outputFactory.createXMLEventWriter(out);
    XMLEvent event;// w w  w . ja v a  2  s . c om

    boolean deleteSection = false;
    while (reader.hasNext()) {
        event = reader.nextEvent();
        if (event.getEventType() == XMLStreamConstants.START_ELEMENT
                && event.asStartElement().getName().toString().equalsIgnoreCase("companies")) {
            deleteSection = true;
            continue;
        } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
                && (event.asEndElement().getName().toString().equalsIgnoreCase("companies"))) {
            deleteSection = false;
            continue;
        } else if (deleteSection) {
            continue;
        } else {
            writer.add(event);
        }
    }
}

From source file:WpRDFFunctionLibrary.java

public static void mergeGpmltoSingleFile(String gpmlLocation) throws IOException, XMLStreamException,
        ParserConfigurationException, SAXException, TransformerException {
    // Based on: http://stackoverflow.com/questions/10759775/how-to-merge-1000-xml-files-into-one-in-java
    //for (int i = 1; i < 8 ; i++) {      
    Writer outputWriter = new FileWriter("/tmp/WpGPML.xml");
    XMLOutputFactory xmlOutFactory = XMLOutputFactory.newFactory();
    XMLEventWriter xmlEventWriter = xmlOutFactory.createXMLEventWriter(outputWriter);
    XMLEventFactory xmlEventFactory = XMLEventFactory.newFactory();

    xmlEventWriter.add(xmlEventFactory.createStartDocument("ISO-8859-1", "1.0"));
    xmlEventWriter.add(xmlEventFactory.createStartElement("", null, "PathwaySet"));
    xmlEventWriter.add(xmlEventFactory.createAttribute("creationData", basicCalls.now()));
    XMLInputFactory xmlInFactory = XMLInputFactory.newFactory();

    File dir = new File(gpmlLocation);

    File[] rootFiles = dir.listFiles();
    //the section below is only in case of analysis sets
    for (File rootFile : rootFiles) {
        String fileName = FilenameUtils.removeExtension(rootFile.getName());
        System.out.println(fileName);
        String[] identifiers = fileName.split("_");
        System.out.println(fileName);
        String wpIdentifier = identifiers[identifiers.length - 2];
        String wpRevision = identifiers[identifiers.length - 1];
        //Pattern pattern = Pattern.compile("_(WP[0-9]+)_([0-9]+).gpml");
        //Matcher matcher = pattern.matcher(fileName);
        //System.out.println(matcher.find());
        //String wpIdentifier = matcher.group(1);
        File tempFile = new File(constants.localAllGPMLCacheDir() + wpIdentifier + "_" + wpRevision + ".gpml");
        //System.out.println(matcher.group(1));
        //String wpRevision = matcher.group(2);
        //System.out.println(matcher.group(2));
        if (!(tempFile.exists())) {
            System.out.println(tempFile.getName());
            Document currentGPML = basicCalls.openXmlFile(rootFile.getPath());
            basicCalls.saveDOMasXML(WpRDFFunctionLibrary.addWpProvenance(currentGPML, wpIdentifier, wpRevision),
                    constants.localCurrentGPMLCache() + tempFile.getName());
        }/*from  w w  w.ja va  2 s .c  o  m*/
    }

    dir = new File("/tmp/GPML");
    rootFiles = dir.listFiles();
    for (File rootFile : rootFiles) {
        System.out.println(rootFile);
        XMLEventReader xmlEventReader = xmlInFactory.createXMLEventReader(new StreamSource(rootFile));
        XMLEvent event = xmlEventReader.nextEvent();
        // Skip ahead in the input to the opening document element
        try {
            while (event.getEventType() != XMLEvent.START_ELEMENT) {
                event = xmlEventReader.nextEvent();
            }

            do {
                xmlEventWriter.add(event);
                event = xmlEventReader.nextEvent();
            } while (event.getEventType() != XMLEvent.END_DOCUMENT);
            xmlEventReader.close();
        } catch (Exception e) {
            System.out.println("Malformed gpml file");
        }
    }

    xmlEventWriter.add(xmlEventFactory.createEndElement("", null, "PathwaySet"));
    xmlEventWriter.add(xmlEventFactory.createEndDocument());

    xmlEventWriter.close();
    outputWriter.close();
}

From source file:de.tudarmstadt.ukp.integration.alignment.xml.AlignmentXmlWriter.java

public AlignmentXmlWriter(OutputStream out) throws IOException {

    try {//w ww . j a  v a  2s.c  o  m
        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
        xmlEventWriter = xmlOutputFactory.createXMLEventWriter(out);

        JAXBContext context = JAXBContext.newInstance(XmlMeta.class, Alignments.class); //Source.class

        marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); // no document level events
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        xmlef = XMLEventFactory.newInstance();
        xmlEventWriter.add(xmlef.createStartDocument());
        xmlEventWriter.add(xmlef.createStartElement("", "", RESOURCE_ALIGNMENT));

    } catch (XMLStreamException e) {
        throw new IOException(e);
    } catch (JAXBException e) {
        throw new IOException(e);
    }

}

From source file:com.github.lindenb.jvarkit.tools.blast.BlastFilterJS.java

@Override
protected Collection<Throwable> call(String inputName) throws Exception {

    final CompiledScript compiledScript;
    Unmarshaller unmarshaller;/*from   ww  w.j a va2 s . com*/
    Marshaller marshaller;
    try {
        compiledScript = super.compileJavascript();

        JAXBContext jc = JAXBContext.newInstance("gov.nih.nlm.ncbi.blast");

        unmarshaller = jc.createUnmarshaller();
        marshaller = jc.createMarshaller();

        XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
        xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        PrintWriter pw = openFileOrStdoutAsPrintWriter();
        XMLOutputFactory xof = XMLOutputFactory.newFactory();
        xof.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.FALSE);
        XMLEventWriter w = xof.createXMLEventWriter(pw);

        StreamSource src = null;
        if (inputName == null) {
            LOG.info("Reading stdin");
            src = new StreamSource(stdin());
        } else {
            LOG.info("Reading file " + inputName);
            src = new StreamSource(new File(inputName));
        }

        XMLEventReader r = xmlInputFactory.createXMLEventReader(src);

        XMLEventFactory eventFactory = XMLEventFactory.newFactory();

        SimpleBindings bindings = new SimpleBindings();
        while (r.hasNext()) {
            XMLEvent evt = r.peek();
            switch (evt.getEventType()) {
            case XMLEvent.START_ELEMENT: {
                StartElement sE = evt.asStartElement();
                Hit hit = null;
                JAXBElement<Hit> jaxbElement = null;
                if (sE.getName().getLocalPart().equals("Hit")) {
                    jaxbElement = unmarshaller.unmarshal(r, Hit.class);
                    hit = jaxbElement.getValue();
                } else {
                    w.add(r.nextEvent());
                    break;
                }

                if (hit != null) {

                    bindings.put("hit", hit);

                    boolean accept = super.evalJavaScriptBoolean(compiledScript, bindings);

                    if (accept) {
                        marshaller.marshal(jaxbElement, w);
                        w.add(eventFactory.createCharacters("\n"));
                    }
                }

                break;
            }
            case XMLEvent.SPACE:
                break;
            default: {
                w.add(r.nextEvent());
                break;
            }
            }
            r.close();
        }
        w.flush();
        w.close();
        pw.flush();
        pw.close();
        return RETURN_OK;
    } catch (Exception err) {
        return wrapException(err);
    } finally {

    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.tiger.TigerXmlWriter.java

@Override
public void process(JCas aJCas) throws AnalysisEngineProcessException {
    OutputStream docOS = null;//from   w  ww .  j  a  va  2s  .  com
    try {
        docOS = getOutputStream(aJCas, filenameSuffix);

        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
        XMLEventWriter xmlEventWriter = new IndentingXMLEventWriter(
                xmlOutputFactory.createXMLEventWriter(docOS));

        JAXBContext context = JAXBContext.newInstance(TigerSentence.class);
        Marshaller marshaller = context.createMarshaller();
        // We use the marshaller only for individual sentences. That way, we do not have to 
        // build the whole TIGER object graph before seralizing, which should safe us some
        // memory.
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

        XMLEventFactory xmlef = XMLEventFactory.newInstance();
        xmlEventWriter.add(xmlef.createStartDocument());
        xmlEventWriter.add(xmlef.createStartElement("", "", "corpus"));
        xmlEventWriter.add(xmlef.createStartElement("", "", "body"));

        int sentenceNumber = 1;
        for (Sentence s : select(aJCas, Sentence.class)) {
            TigerSentence ts = convertSentence(s, sentenceNumber);
            marshaller.marshal(new JAXBElement<TigerSentence>(new QName("s"), TigerSentence.class, ts),
                    xmlEventWriter);
            sentenceNumber++;
        }

        xmlEventWriter.add(xmlef.createEndElement("", "", "body"));
        xmlEventWriter.add(xmlef.createEndElement("", "", "corpus"));
        xmlEventWriter.add(xmlef.createEndDocument());
    } catch (Exception e) {
        throw new AnalysisEngineProcessException(e);
    } finally {
        closeQuietly(docOS);
    }
}

From source file:log4JToXml.xmlToProperties.XmlToLog4jConverterImpl.java

private void addDTDDeclaration(String filename) throws XMLStreamException {
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEvent dtd = eventFactory/*  w  w w .  j  av a 2s  .  c o  m*/
            .createDTD("<!DOCTYPE log4j:configuration SYSTEM \"" + tempDTD.getAbsolutePath() + "\">");

    XMLInputFactory inFactory = XMLInputFactory.newInstance();
    XMLOutputFactory outFactory = XMLOutputFactory.newInstance();

    XMLEventReader reader = inFactory.createXMLEventReader(new StreamSource(filename));
    reader = new DTDReplacer(reader, dtd);
    XMLEventWriter writer = outFactory.createXMLEventWriter(documentStream);
    writer.add(reader);
    writer.flush();

    writer.close();
}

From source file:com.act.lcms.MzMLParser.java

public Iterator<S> getIterator(String inputFile)
        throws ParserConfigurationException, IOException, XMLStreamException {
    DocumentBuilderFactory docFactory = mkDocBuilderFactory();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    final XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
    final XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();

    return new Iterator<S>() {
        boolean inEntry = false;

        XMLEventReader xr = xmlInputFactory.createXMLEventReader(new FileInputStream(inputFile), "utf-8");
        // TODO: is the use of the XML version/encoding tag definitely necessary?
        StringWriter w = new StringWriter().append(XML_PREAMBLE).append("\n");
        XMLEventWriter xw = xmlOutputFactory.createXMLEventWriter(w);

        S next = null;/*w  ww .  j  a  v a2  s.c  om*/

        /* Because we're handling the XML as a stream, we can only determine whether we have another Spectrum to return
         * by attempting to parse the next one.  `this.next()` reads
         */
        private S getNextSpectrum() {
            S spectrum = null;
            if (xr == null || !xr.hasNext()) {
                return null;
            }

            try {
                while (xr.hasNext()) {
                    XMLEvent e = xr.nextEvent();
                    if (!inEntry && e.isStartElement()
                            && e.asStartElement().getName().getLocalPart().equals((SPECTRUM_OBJECT_TAG))) {
                        xw.add(e);
                        inEntry = true;
                    } else if (e.isEndElement()
                            && e.asEndElement().getName().getLocalPart().equals(SPECTRUM_OBJECT_TAG)) {
                        xw.add(e);
                        xw.flush();
                        /* TODO: the XMLOutputFactory docs don't make it clear if/how events can be written directly into a new
                         * document structure, so we incur the cost of extracting each spectrum entry, serializing it, and
                         * re-reading it into its own document so it can be handled by XPath.  Master this strange corner of the
                         * Java ecosystem and get rid of <></>his doc -> string -> doc conversion. */
                        Document doc = docBuilder.parse(new ReaderInputStream(new StringReader(w.toString())));
                        spectrum = handleSpectrumEntry(doc);
                        xw.close();
                        /* Note: this can also be accomplished with `w.getBuffer().setLength(0);`, but using a new event writer
                         * seems safer. */
                        w = new StringWriter();
                        w.append(XML_PREAMBLE).append("\n");
                        xw = xmlOutputFactory.createXMLEventWriter(w);
                        inEntry = false;
                        // Don't stop parsing if handleSpectrumEntry didn't like this spectrum document.
                        if (spectrum != null) {
                            break;
                        }
                    } else if (inEntry) {
                        // Add this element if we're in an entry
                        xw.add(e);
                    }
                }

                // We've reached the end of the document; close the reader to show that we're done.
                if (!xr.hasNext()) {
                    xr.close();
                    xr = null;
                }
            } catch (Exception e) {
                // TODO: do better.  We seem to run into this sort of thing with Iterators a lot...
                throw new RuntimeException(e);
            }

            return spectrum;
        }

        private S tryParseNext() {
            // Fail the attempt if the reader is closed.
            if (xr == null || !xr.hasNext()) {
                return null;
            }

            // No checks on whether we already have a spectrum stored: we expect the callers to do that.
            return getNextSpectrum();
        }

        @Override
        public boolean hasNext() {
            // Prime the pump if the iterator doesn't have a value stored yet.
            if (this.next == null) {
                this.next = tryParseNext();
            }

            // If we have an entry waiting, return true; otherwise read the next entry and return true if successful.
            return this.next != null;
        }

        @Override
        public S next() {
            // Prime the pump like we do in hasNext().
            if (this.next == null) {
                this.next = tryParseNext();
            }

            // Take available spectrum and return it.
            S res = this.next;
            /* Advance to the next element immediately, making next() do the heavy lifting most of the time.  Otherwise,
             * the parsing will resume on hasNext(), which seems like it ought to be a light-weight operation. */
            this.next = tryParseNext();

            return res;
        }

    };
}