Java生成XML文件
2017-01-23 22:51
369 查看
《Java眼中的XML ---文件写入》
四种方法用Java生成一个XML文件。1.通过DOM方式生成XML文档
import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; public class JDOMCreateTest { public void create() { Element bookStore = new Element("bookStore"); Document document = new Document(bookStore); Element book = new Element("book"); bookStore.addContent(book); book.setAttribute("category", "e-sport"); Element title = new Element("title"); title.setText("全职高手"); book.addContent(title); Element author = new Element("author"); book.addContent(author); Format format = Format.getCompactFormat(); format.setIndent(" "); format.setEncoding("GBK"); XMLOutputter outputter = new XMLOutputter(format); try { outputter.output(document, new FileOutputStream(new File("books.xml"))); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { new JDOMCreateTest().create(); } }
JDOMCreateTest.java
生成文件效果
<?xml version="1.0" encoding="GBK"?> <bookStore> <book category="e-sport"> <title>全职高手</title> <author /> </book> </bookStore>
相关文章推荐
- Java复习第三天-继承的注意事项
- 关于java高并发问题总结
- JavaSE 学习参考:逻辑运算符
- Java 脚本支持
- 小博老师解析Java核心技术 ——AJAX第三弹
- hashmap java用法
- java基础六对象
- Java并发中的Copy-On-Write容器
- java合并单元格同时导出excel
- 博为峰Java技术文章 ——JavaSE Swing SpringLayout布局管理器II
- 解密Java内存溢出之持久代
- Java NIO Selector详解(含多人聊天室实例)
- 介绍如何安装开源性能测试工具——JMeter
- 博为峰Java技术文章 ——JavaSE Swing GroupLayout布局管理器
- java保留两位小数
- Leetcode刷题(Single Number)
- java基础知识
- Leetcode刷题(Nim Game)
- Excel 的基本操作
- 【Java Web】页面包含