import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; public class DomXml { @Test public void test(){ Long start = System.currentTimeMillis(); createXml(); System.out.println("運行時間:"+ (System.currentTimeMillis() - start)); } /** * 生成xml方法 */ public static void createXml(){ try { // 建立解析器工廠 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder db = factory.newDocumentBuilder(); Document document = db.newDocument(); // 不顯示standalone="no" document.setXmlStandalone(true); Element bookstore = document.createElement("bookstore"); // 向bookstore根節點中添加子節點book Element book = document.createElement("book"); Element name = document.createElement("name"); // 不顯示內容 name.setNodeValue("很差使"); name.setTextContent("雷神"); book.appendChild(name); // 爲book節點添加屬性 book.setAttribute("id", "1"); // 將book節點添加到bookstore根節點中 bookstore.appendChild(book); // 將bookstore節點(已包含book)添加到dom樹中 document.appendChild(bookstore); // 建立TransformerFactory對象 TransformerFactory tff = TransformerFactory.newInstance(); // 建立 Transformer對象 Transformer tf = tff.newTransformer(); // 輸出內容是否使用換行 tf.setOutputProperty(OutputKeys.INDENT, "yes"); // 建立xml文件並寫入內容 tf.transform(new DOMSource(document), new StreamResult(new File("book1.xml"))); System.out.println("生成book1.xml成功"); } catch (Exception e) { e.printStackTrace(); System.out.println("生成book1.xml失敗"); } } }
生成結果:
java
import java.io.File; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; 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.junit.Test; import org.xml.sax.helpers.AttributesImpl; public class SaxXml { @Test public void test(){ List<Book> bList = new ArrayList<Book>(); Book b = new Book(); b.setName("冰與火之歌"); b.setAuthor("喬治馬丁"); b.setId("1"); b.setLanguage("English"); b.setPrice("86"); b.setYear("2014"); bList.add(b); Long start = System.currentTimeMillis(); createXml(bList); System.out.println("運行時間:"+ (System.currentTimeMillis() - start)); } // 生成xml public static void createXml(List<Book> bList){ // 一、建立一個SAXTransformerFactory類的對象 SAXTransformerFactory tff = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); try { // 二、經過SAXTransformerFactory建立一個TransformerHandler的對象 TransformerHandler handler = tff.newTransformerHandler(); // 三、經過handler建立一個Transformer對象 Transformer tr = handler.getTransformer(); // 四、經過Transformer對象對生成的xml文件進行設置 // 設置編碼方式 tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // 設置是否換行 tr.setOutputProperty(OutputKeys.INDENT, "yes"); // 五、建立一個Result對象 File f = new File("src/newbooks.xml"); // 判斷文件是否存在 if(!f.exists()){ f.createNewFile(); } Result result = new StreamResult(new FileOutputStream(f)); // 六、使RESULT與handler關聯 handler.setResult(result); // 打開document handler.startDocument(); AttributesImpl attr = new AttributesImpl(); handler.startElement("", "", "bookstore", attr); attr.clear(); for (Book book : bList) { attr.clear(); attr.addAttribute("", "", "id", "", book.getId()); handler.startElement("", "", "book", attr); // 建立name attr.clear(); handler.startElement("", "", "name", attr); handler.characters(book.getName().toCharArray(), 0, book.getName().length()); handler.endElement("", "", "name"); // 建立year attr.clear(); handler.startElement("", "", "year", attr); handler.characters(book.getYear().toCharArray(), 0, book.getYear().length()); handler.endElement("", "", "year"); // 建立author if(book.getAuthor() != null && !"".equals(book.getAuthor().trim())){ attr.clear(); handler.startElement("", "", "author", attr); handler.characters(book.getAuthor().toCharArray(), 0, book.getAuthor().length()); handler.endElement("", "", "author"); } // 建立price if(book.getPrice() != null && !"".equals(book.getPrice().trim())){ attr.clear(); handler.startElement("", "", "price", attr); handler.characters(book.getPrice().toCharArray(), 0, book.getPrice().length()); handler.endElement("", "", "price"); } // 建立language if(book.getLanguage() != null && !"".equals(book.getLanguage().trim())){ attr.clear(); handler.startElement("", "", "language", attr); handler.characters(book.getLanguage().toCharArray(), 0, book.getLanguage().length()); handler.endElement("", "", "language"); } handler.endElement("", "", "book"); } handler.endElement("", "", "bookstore"); // 關閉document handler.endDocument(); System.out.println("生成newbooks.xml成功"); } catch (Exception e) { e.printStackTrace(); System.out.println("生成newbooks.xml失敗"); } } }
生成結果:
app
import java.io.File; import java.io.FileOutputStream; import org.jdom.Document; import org.jdom.Element; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import org.junit.Test; public class JDomXml { @Test public void test(){ Long start = System.currentTimeMillis(); createXml(); System.out.println("運行時間:"+ (System.currentTimeMillis() - start)); } /** * 生成xml方法 */ public static void createXml(){ try { // 一、生成一個根節點 Element rss = new Element("rss"); // 二、爲節點添加屬性 rss.setAttribute("version", "2.0"); // 三、生成一個document對象 Document document = new Document(rss); Element channel = new Element("channel"); rss.addContent(channel); Element title = new Element("title"); title.setText("國內最新新聞"); channel.addContent(title); Format format = Format.getCompactFormat(); // 設置換行Tab或空格 format.setIndent(" "); format.setEncoding("UTF-8"); // 四、建立XMLOutputter的對象 XMLOutputter outputer = new XMLOutputter(format); // 五、利用outputer將document轉換成xml文檔 File file = new File("rssNew.xml"); outputer.output(document, new FileOutputStream(file)); System.out.println("生成rssNew.xml成功"); } catch (Exception e) { System.out.println("生成rssNew.xml失敗"); } } }
生成結果:
dom
import java.io.File; import java.io.FileOutputStream; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import org.junit.Test; public class Dom4jXml { @Test public void test(){ Long start = System.currentTimeMillis(); createXml(); System.out.println("運行時間:"+ (System.currentTimeMillis() - start)); } /** * 生成xml方法 */ public static void createXml(){ try { // 一、建立document對象 Document document = DocumentHelper.createDocument(); // 二、建立根節點rss Element rss = document.addElement("rss"); // 三、向rss節點添加version屬性 rss.addAttribute("version", "2.0"); // 四、生成子節點及子節點內容 Element channel = rss.addElement("channel"); Element title = channel.addElement("title"); title.setText("國內最新新聞"); // 五、設置生成xml的格式 OutputFormat format = OutputFormat.createPrettyPrint(); // 設置編碼格式 format.setEncoding("UTF-8"); // 六、生成xml文件 File file = new File("rss.xml"); XMLWriter writer = new XMLWriter(new FileOutputStream(file), format); // 設置是否轉義,默認使用轉義字符 writer.setEscapeText(false); writer.write(document); writer.close(); System.out.println("生成rss.xml成功"); } catch (Exception e) { e.printStackTrace(); System.out.println("生成rss.xml失敗"); } } }
生成結果:
ui
/** * 四種方式總結 * * dom基於tree,sax基於事件,JDOM和DOM4J基於底層API * * dom生成的內容會保存到內存中,方便刪除和修改 * sax不能修改已經生成的標籤 * * 添加JUnit在Libraries選擇Add Library中的JUnit便可 * */
/** * 四種方式總結 * * dom基於tree,sax基於事件,JDOM和DOM4J基於底層API * * dom生成的內容會保存到內存中,方便刪除和修改 * sax不能修改已經生成的標籤 * * 添加JUnit在Libraries選擇Add Library中的JUnit便可 * */編碼