SAXCreateXMLDocument
Posted zhangyugeng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SAXCreateXMLDocument相关的知识,希望对你有一定的参考价值。
package creatXMLDovument; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; 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 org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; public class SAXCreateXMLDocument { public static void main(String[] args) { //1.创建sax转换器工厂 SAXTransformerFactory factory=(SAXTransformerFactory) SAXTransformerFactory.newInstance(); try { //2.创建转换器处理器 TransformerHandler handler=factory.newTransformerHandler(); //3.处理器获得转换器 Transformer tf=handler.getTransformer(); //4.通过Transformer设置XML文件 tf.setOutputProperty(OutputKeys.ENCODING, "utf-8"); tf.setOutputProperty(OutputKeys.INDENT,"yes"); //5.创建一个result对象 File f=new File("src/book3.xml"); if(!f.exists()) { f.createNewFile(); } //不明白 /* StreamResult Construct a StreamResult from a byte stream. Normally, a stream should be used rather than a reader, so that the transformer may use instructions contained in the transformation instructions to control the encoding. 从一个字节流构造一个流结果。正常来说,应该使用一个流 一个读取器,所以这个转换器可能使用包含在这个转换的指令去控制编码。 */ /* Result * An object that implements this interface contains the information needed to build a transformation result tree. 实现该接口的对象包含构建所需的信息转换结果树 */ Result result=new StreamResult(new FileOutputStream(f)); //不明白 handler.setResult(result); //不明白 AttributesImpl atts=new AttributesImpl(); handler.startDocument(); handler.startElement("", "", "bookstore", atts); atts.clear(); handler.startElement("", "", "book", atts); atts.addAttribute("", "", "id", "", "1"); atts.clear(); handler.startElement("", "", "name", atts); handler.characters("叶兰".toCharArray(), 0, "叶兰".length()); handler.endElement("", "", "name"); handler.startElement("", "", "age", atts); handler.characters("19".toCharArray(), 0, "19".length()); handler.endElement("", "", "age"); handler.endElement("", "", "book"); handler.endElement("", "", "bookstore"); handler.endDocument(); } catch (TransformerConfigurationException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); }catch (SAXException e) { e.printStackTrace(); } } }
以上是关于SAXCreateXMLDocument的主要内容,如果未能解决你的问题,请参考以下文章