How to write unescaped XML to XMLStreamWriter?

后端 未结 3 1772
不知归路
不知归路 2021-01-06 01:31

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

3条回答
  •  醉梦人生
    2021-01-06 01:51

    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  tag. */
            xsw.writeCharacters("");
            xsw.flush();
    
            OutputStreamWriter osw = new OutputStreamWriter(stream);
            osw.write("Hello World");
            osw.flush();
    
            xsw.writeEndElement();
            xsw.writeEndElement();
            xsw.writeEndDocument();
            xsw.close();
        }
    
    }
    

提交回复
热议问题