为了创建大型XML文件,我们决定使用StAX API。基本结构是使用低级API构建的:createStartDocument(),createStartElement()。这按预期工作。
但是,在某些情况下,我们希望附加驻留在String中的现有XML数据(从数据库中检索)。以下代码段说明了这一点:
import java.lang.*;
import java.io.*;
import javax.xml.stream.*;
public class Example {
public static void main(String... args) throws XMLStreamException {
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
XMLEventFactory eventFactory = XMLEventFactory.newInstance();
StringWriter writer = new StringWriter();
XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(writer);
eventWriter.add(eventFactory.createStartDocument("UTF-8", "1.0"));
eventWriter.add(eventFactory.createStartElement("ns0", "http://example.org", "root"));
eventWriter.add(eventFactory.createNamespace("ns0", "http://example.org"));
//In here, we want to append a piece of XML which is stored in a string variable.
String xml = "<fragments><fragment><data>This is pure text.</data></fragment></fragments>";
eventWriter.add(inputFactory.createXMLEventReader(new StringReader(xml)));
eventWriter.add(eventFactory.createEndDocument());
System.out.println(writer.toString());
}
}
使用上面的代码,根据实现,我们没有得到预期的结果:
<?xml version="1.0" ... <fragments><fragment>...
- &gt;这会导致无效的XML。我还尝试使用以下方法附加XML:
eventFactory.createCharacters(xml);
这里的问题是,即使附加了XML,&lt;和&gt;被转换为&amp; lt和&amp; gt。因此,这会导致XML无效。
我是否缺少允许我简单地将String附加为XML的API?
答案 0 :(得分:3)
如有必要,您可以先使用任何StartDocument:
String xml = "<fragments><fragment><data>This is pure text.</data></fragment></fragments>";
XMLEventReader xer = inputFactory.createXMLEventReader(new StringReader(xml));
if (xer.peek().isStartDocument())
{
xer.nextEvent();
}
eventWriter.add(xer);