How to write unescaped XML to XMLStreamWriter?

心已入冬 提交于 2019-12-30 06:50:47

问题


I have a number of small XML chunks, that should be embedded in one big XML as child elements. Is there any way to write these chunks to XMLStreamWriter without escaping them?


回答1:


Below are a couple of options for handling this:

Option #1 - Use javax.xml.transform.Transformer

You could use a javax.xml.transform.Transformer to transform a StreamSource representing your XML fragment onto your StAXResult which is wrapping your XMLStreamWriter.

Option #2 - Interact Directly with the OuputStream

Alternatively you could do something like the following. You can leverage flush() to force the XMLStreamWriter to output its contents. Then you'll note that I do xsw.writeCharacters("") this forces the start element to end for bar before writing the nested XML as a String. The sample code below needs to be flushed out to properly handle encoding issues.

import java.io.*;
import javax.xml.stream.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        OutputStream stream = System.out;

        XMLOutputFactory xof = XMLOutputFactory.newFactory();
        XMLStreamWriter xsw = xof.createXMLStreamWriter(stream);

        xsw.writeStartDocument();
        xsw.writeStartElement("foo");
        xsw.writeStartElement("bar");

        /* Following line is very important, without it unescaped data 
           will appear inside the <bar> tag. */
        xsw.writeCharacters("");
        xsw.flush();

        OutputStreamWriter osw = new OutputStreamWriter(stream);
        osw.write("<baz>Hello World<baz>");
        osw.flush();

        xsw.writeEndElement();
        xsw.writeEndElement();
        xsw.writeEndDocument();
        xsw.close();
    }

}



回答2:


woodstox has a stax implementation and their XMLStreamWriter2 class has a writeRaw() call. We have the same need and this gave us a very nice solution.




回答3:


final XMLOutputFactory streamWriterFactory = XMLOutputFactory.newFactory();
streamWriterFactory.setProperty("escapeCharacters", false);

From here



来源:https://stackoverflow.com/questions/19998460/how-to-write-unescaped-xml-to-xmlstreamwriter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!