- Java XML 教程
- Java XML 主页
- Java XML 概述
- Java XML 解析器
- Java DOM 解析器
- Java DOM 解析器
- 解析XML文档
- 查询XML文档
- 创建 XML 文档
- 修改XML文档
- Java SAX 解析器
- Java SAX 解析器
- 解析XML文档
- 查询XML文档
- 创建 XML 文档
- 修改XML文档
- JDOM XML 解析器
- JDOM XML 解析器
- 解析XML文档
- 查询XML文档
- 创建 XML 文档
- 修改XML文档
- Java StAX 解析器
- Java StAX 解析器
- 解析XML文档
- 查询XML文档
- 创建 XML 文档
- 修改XML文档
- Java XPath 解析器
- Java XPath 解析器
- 解析XML文档
- 查询XML文档
- 创建 XML 文档
- 修改XML文档
- Java DOM4J 解析器
- Java DOM4J 解析器
- 解析XML文档
- 查询XML文档
- 创建 XML 文档
- 修改XML文档
- Java XML 有用资源
- Java XML - 问题与解答
- Java XML - 快速指南
- Java XML - 有用的资源
- Java XML - 讨论
Java StAX 解析器 - 创建 XML 文档
演示示例
这是我们需要创建的 XML -
<?xml version = "1.0" encoding = "UTF-8" standalone = "no"?> <cars> <supercars company = "Ferrari"> <carname type = "formula one">Ferrari 101</carname> <carname type = "sports">Ferrari 202</carname> </supercars> </cars>
StAXCreateXMLDemo.java
package com.tutorialspoint.xml; import java.io.IOException; import java.io.StringWriter; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; public class StAXCreateXMLDemo { public static void main(String[] args) { try { StringWriter stringWriter = new StringWriter(); XMLOutputFactory xMLOutputFactory = XMLOutputFactory.newInstance(); XMLStreamWriter xMLStreamWriter = xMLOutputFactory.createXMLStreamWriter(stringWriter); xMLStreamWriter.writeStartDocument(); xMLStreamWriter.writeStartElement("cars"); xMLStreamWriter.writeStartElement("supercars"); xMLStreamWriter.writeAttribute("company", "Ferrari"); xMLStreamWriter.writeStartElement("carname"); xMLStreamWriter.writeAttribute("type", "formula one"); xMLStreamWriter.writeCharacters("Ferrari 101"); xMLStreamWriter.writeEndElement(); xMLStreamWriter.writeStartElement("carname"); xMLStreamWriter.writeAttribute("type", "sports"); xMLStreamWriter.writeCharacters("Ferrari 202"); xMLStreamWriter.writeEndElement(); xMLStreamWriter.writeEndElement(); xMLStreamWriter.writeEndDocument(); xMLStreamWriter.flush(); xMLStreamWriter.close(); String xmlString = stringWriter.getBuffer().toString(); stringWriter.close(); System.out.println(xmlString); } catch (XMLStreamException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
这将产生以下结果 -
<?xml version = "1.0" encoding = "UTF-8" standalone = "no"?> <cars> <supercars company = "Ferrari"> <carname type = "formula one">Ferrari 101</carname> <carname type = "sports">Ferrari 202</carname> </supercars> </cars>