您的位置:首页 > 编程语言 > Java开发

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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: