SAX生成xml文件

来源:互联网 发布:js tochararray 编辑:程序博客网 时间:2024/06/05 16:24
package test;
import java.io.File;
import java.io.FileOutputStream;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.helpers.AttributesImpl;
public class SAXCreator {
public static void main(String[] args) throws Exception {
// 创建SAX转换工厂
SAXTransformerFactory sff = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
// 转换处理器,侦听 SAX ContentHandler
// 解析事件,并将它们转换为结果树 Result
TransformerHandler th = sff.newTransformerHandler();
// 将源树转换为结果树
Transformer transformer = th.getTransformer();
// 设置字符编码
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
// 是否缩进
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
File file = new File("sax.xml");
// 判断是否存在
if (!file.exists()) {
// 创建文件名
file.createNewFile();
FileOutputStream out = new FileOutputStream(file);
// 构建转换结果树所需的信息
Result resultStr = new StreamResult(out);
// setResult() 必须在 startDocument() 之前调用
th.setResult(resultStr);
th.startDocument();
}
// 行结点属性
AttributesImpl attr = new AttributesImpl();
// 创建根元素<cities>,并设置其属性为空
th.startElement("", "", "cities", attr);
th.startElement("", "", "calsses", attr);
// 创建一级子元素<group>,并设置其属性
attr.clear();
attr.addAttribute("", "name", "name", "", "张三");
attr.addAttribute("", "num", "num", "", "10");
th.startElement("", "", "group", attr);
// 创建二级子元素<person>,并设置其属性
attr.clear();
attr.addAttribute("", "name", "name", "", "小明");
attr.addAttribute("", "age", "age", "", "7");
//接受元素的开始
th.startElement("", "", "person", attr);
// 创建三级子元素<chinese>,并设置其值
attr.clear();
        th.startElement("", "", "chinese", attr);  
        th.characters("语文90".toCharArray(), 0, "语文90".length());  
        th.endElement("", "", "chinese");  
        //创建四级子元素<english>,并设置其值  
        th.startElement("", "", "english", attr);  
        th.characters("英语80".toCharArray(), 0, "数学80".length());  
        //接收元素结束的通知
th.endElement("", "", "english");
th.endElement("", "", "person");
th.endElement("", "", "group");
th.endElement("", "calsses", "calsses");
//接收文档的结尾的通知
th.endDocument();
System.out.println(file.getAbsolutePath());
}
}
原创粉丝点击