如何将非转义XML写入XMLStreamWriter? [英] How to write unescaped XML to XMLStreamWriter?

查看:346
本文介绍了如何将非转义XML写入XMLStreamWriter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多小的XML块,应该作为子元素嵌入到一个大的XML中。有没有办法将这些块写入 XMLStreamWriter 而不转义它们?

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?

推荐答案

以下是处理此问题的几个选项:

Below are a couple of options for handling this:

您可以使用 javax.xml.transform.Transformer 转换 StreamSource 将您的XML片段表示到您的 StAXResult ,它包装您的 XMLStreamWriter

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

或者你可以做类似以下的事情。您可以利用 flush()强制 XMLStreamWriter 输出其内容。然后你会注意到我做 xsw.writeCharacters()这会强制start元素结束 bar 在将嵌套XML写为 String 之前。需要刷新下面的示例代码以正确处理编码问题。

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();
    }

}

这篇关于如何将非转义XML写入XMLStreamWriter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆