关闭

用JDK自带方法 写入XML文档

73人阅读 评论(0) 收藏 举报
<span style="font-size:18px;">package testXMLStreamWriter;

import java.io.StringWriter;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

public class Test {
	XMLStreamWriter xsw = null;
	public static void main(String[] args) {
		StringWriter str = new StringWriter();
		Test t = new Test();
		XMLStreamWriter xsw = t.getXMLStreamReader(str);//调用创建XMl输出流的方法返回一个  XML输出流,输出到str
		try {
			xsw.writeStartDocument("UTF-8","1.0");//声明版本号<?xml version="1.0" encoding="UTF-8"?>
			xsw.writeStartElement("java");//开始标记<java>
			
			xsw.writeStartElement("API");
			xsw.writeAttribute("流","asd");//不带前缀的属性 <API 流=asd></API>
			xsw.writeEndElement();
			
			xsw.writeStartElement("Excption");
			xsw.writeCharacters("Runtime,IO,ClassNotFound");//内容<Exception> Runtime,IO,ClassNotFound </Exception>
			xsw.writeEndElement();
			
			xsw.writeEndElement();//结束标记</java>
			xsw.writeEndDocument();//结束
			
			System.out.println(str.toString());
		} catch (XMLStreamException e) {
			e.printStackTrace();
		}
	}
	
	public XMLStreamWriter getXMLStreamReader(StringWriter str){
		XMLOutputFactory xif = XMLOutputFactory.newInstance();//工厂创建
		try {
			xsw =  xif.createXMLStreamWriter(str);//创建XML输出流
		} catch (XMLStreamException e) {
			e.printStackTrace();
			return null;
		}
		return xsw;
	}
	 
}
</span>

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1464次
    • 积分:46
    • 等级:
    • 排名:千里之外
    • 原创:3篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章存档