Java StAX:XMLStreamWriter-游标编写器API
时间:2020-01-09 10:36:32 来源:igfitidea点击:
Java StAX API中的XMLStreamWriter类允许我们将XML事件(元素,属性等)写入"写程序"," OutputStream"或者"结果"(特殊的JAXP对象)。
这是一个简单的示例,使用FileWriter
将一系列事件写入磁盘:
XMLOutputFactory factory = XMLOutputFactory.newInstance(); try { XMLStreamWriter writer = factory.createXMLStreamWriter( new FileWriter("data\output2.xml")); writer.writeStartDocument(); writer.writeStartElement("document"); writer.writeStartElement("data"); writer.writeAttribute("name", "value"); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); writer.close(); } catch (XMLStreamException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
执行此代码的结果是以下XML文件(为便于阅读插入了换行符):
<?xml version='1.0' encoding='utf-8'?> <document><data name="value"></data></document>