Java:XML篇,使用SAX写入XML数据
生活随笔
收集整理的這篇文章主要介紹了
Java:XML篇,使用SAX写入XML数据
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 描述
參考:http://blog.csdn.net/hairongtian/article/details/7525292,Java中用SAX解析XML,具體包括讀寫,這篇是寫入示范。
2. 示范代碼
package com.clzhang.sample.xml;import java.io.*; import java.util.*;import javax.xml.transform.OutputKeys; 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.SAXException;// SAX寫入XML測試 // 參考:http://blog.csdn.net/hairongtian/article/details/7525292 public class SAXWriteTest {// 句柄private TransformerHandler handler = null;// 輸出流private OutputStream outStream = null;// 根節點private String rootElement;public SAXWriteTest(String fileName, String rootElement) throws Exception {this.rootElement = rootElement;// 創建句柄,并設置初始參數SAXTransformerFactory fac = (SAXTransformerFactory) SAXTransformerFactory.newInstance();handler = fac.newTransformerHandler();Transformer transformer = handler.getTransformer();transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");transformer.setOutputProperty(OutputKeys.INDENT, "yes");transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");outStream = new FileOutputStream(fileName);handler.setResult(new StreamResult(outStream));System.out.println("初始化成功");}public void start() throws Exception {handler.startDocument();handler.startElement("", "", rootElement, null);System.out.println("文檔開始...");}// 這個函數是最重要的,它可以控制各個細節:是否寫入屬性值,文本值又是多少等等public void write(HashMap<String, String> map, String element)throws SAXException {handler.startElement("", "", element, null);Iterator<String> it = map.keySet().iterator();while (it.hasNext()) {String key = (String) it.next();String value = map.get(key);handler.startElement("", "", key, null);handler.characters(value.toCharArray(), 0, value.length());handler.endElement("", "", key);}handler.endElement("", "", element);System.out.println("寫入元素成功!");}public void end() throws Exception {handler.endElement("", "", rootElement);handler.endDocument();outStream.close();System.out.println("文檔結束!");}public static void main(String[] args) throws Exception {SAXWriteTest xml = new SAXWriteTest("student.xml", "students");xml.start();HashMap<String, String> map = new HashMap<String, String>();map.put("id", "20050505");map.put("name", "zhaobenshan");map.put("age", "21");map.put("classes", "Act051");xml.write(map, "student");map = new HashMap<String, String>();map.put("id", "20050506");map.put("name", "songdandan");map.put("age", "20");map.put("classes", "Act052");xml.write(map, "student");map = new HashMap<String, String>();map.put("id", "20050507");map.put("name", "fanchushi");map.put("age", "21");map.put("classes", "Act051");xml.write(map, "student");xml.end();} }?
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的Java:XML篇,使用SAX写入XML数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Jupyter-Notebook插入公式
- 下一篇: mysql主从日志的定期清理