package com.sax;
import org.xml.sax.helpers.AttributesImpl;
import javax.xml.crypto.dsig.Transform;
import javax.xml.stream.events.Attribute;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
public class BuildXMLMain {
public static void main(String[] args) throws Exception {
//创建 保存XML的 结果流对象
Result resultXML=new StreamResult(new File("F://first1.xml"));
//获取 SAX生成 工厂对象实例
SAXTransformerFactory saxTransformerFactory=(SAXTransformerFactory)SAXTransformerFactory.newInstance();
//获取SAX生成 处理者对象
TransformerHandler transformerHandler=saxTransformerFactory.newTransformerHandler();
transformerHandler.setResult(resultXML);
//获取SAX生成器
Transformer transformer=transformerHandler.getTransformer();
//允许生成一些额外的空格
transformer.setOutputProperty(OutputKeys.INDENT,"yes");
//生成文档的开始
transformerHandler.startDocument();
AttributesImpl attributes=new AttributesImpl();
transformerHandler.startElement("","","书籍列表",attributes);
transformerHandler.startElement("","","计算机书籍",attributes);
transformerHandler.startElement("","","书名",attributes);
transformerHandler.characters("1".toCharArray(),0,"1".length());
transformerHandler.endElement("","","书名");
transformerHandler.startElement("","","作者",attributes);
transformerHandler.characters("1".toCharArray(),0,"1".length());
transformerHandler.endElement("","","作者");
transformerHandler.startElement("","","价格",attributes);
transformerHandler.characters("1".toCharArray(),0,"1".length());
transformerHandler.endElement("","","价格");
transformerHandler.endElement("","","计算机书籍");
//第二本书
transformerHandler.startElement("","","计算机书籍",attributes);
transformerHandler.startElement("","","书名",attributes);
transformerHandler.characters("2".toCharArray(),0,"2".length());
transformerHandler.endElement("","","书名");
transformerHandler.startElement("","","作者",attributes);
transformerHandler.characters("2".toCharArray(),0,"2".length());
transformerHandler.endElement("","","作者");
transformerHandler.startElement("","","价格",attributes);
transformerHandler.characters("2".toCharArray(),0,"2".length());
transformerHandler.endElement("","","价格");
transformerHandler.endElement("","","计算机书籍");
transformerHandler.endElement("","","书籍列表");
//文档生成结束
transformerHandler.endDocument();
System.out.println("XML文档生成成功");
}
}