开发手册 欢迎您!
软件开发者资料库

StAX Parser - 创建XML文档

Apache Xerces StAX Parser创建XML文档 - 从基本到高级概念的简单简单步骤学习Apache Xerces,其中包括概述,Apache Xerces XML Parsers,DOM Parser,Parse XML文档,查询XML文档,创建XML文档,修改XML Document,SAX Parser,StAX Parser。

演示示例

以下是我们需要创建的XML :  

      Ferrari 101   Ferrari 202

演示示例

StAXCreateXMLDemo.java

package com.it1352.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();      }   }}

上述程序将产生以下结果 :

Ferrari 101Ferrari 202