能举个XMLStreamWriterImpl的例子吗
时间: 2024-03-14 18:42:50 浏览: 23
当使用XMLStreamWriterImpl时,通常需要创建一个XMLStreamWriter实例,然后使用该实例调用各种方法来编写XML文档。下面是一个简单的例子,演示如何使用XMLStreamWriterImpl来创建一个包含一个根元素和两个子元素的XML文档:
```java
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.FileWriter;
import java.io.IOException;
public class XMLWriterExample {
public static void main(String[] args) {
try {
XMLOutputFactory factory = XMLOutputFactory.newInstance();
XMLStreamWriter writer = factory.createXMLStreamWriter(new FileWriter("output.xml"));
// 写入XML文档头部
writer.writeStartDocument("1.0");
// 写入根元素
writer.writeStartElement("root");
// 写入第一个子元素
writer.writeStartElement("child1");
writer.writeAttribute("attribute1", "value1");
writer.writeCharacters("text1");
writer.writeEndElement();
// 写入第二个子元素
writer.writeStartElement("child2");
writer.writeAttribute("attribute2", "value2");
writer.writeCharacters("text2");
writer.writeEndElement();
// 写入根元素结束标签
writer.writeEndElement();
// 关闭XMLStreamWriter
writer.close();
System.out.println("XML文档已生成!");
} catch (XMLStreamException | IOException e) {
e.printStackTrace();
}
}
}
```
该程序将在当前目录下创建一个名为"output.xml"的XML文件,包含如下内容:
```xml
<?xml version="1.0" ?><root><child1 attribute1="value1">text1</child1><child2 attribute2="value2">text2</child2></root>
```
需要注意的是,XMLStreamWriterImpl不是线程安全的,因此在多线程环境下需要采用线程安全的方式来使用它。