昨天在网上找了找,终于发现了我要的东西,哈哈,网络真是个好东西。
下面是代码:
package test;
/*
* 创建日期 2005-4-17
*
* TODO 要更改此生成的文件的模板,请转至
* 窗口 - 首选项 - Java - 代码样式 - 代码模板
*/
/**
* @author johnstom
*
* TODO 要更改此生成的类型注释的模板,请转至 窗口 - 首选项 - Java - 代码样式 - 代码模板
*/
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
public class Writexml {
private Document document;
private String filename;
public Writexml(String name) throws ParserConfigurationException {
filename = name;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.newDocument();
}
public void toWrite(String mytitle, String mycontent, String myprice) {
Element root = document.createElement("WorkShop");
document.appendChild(root);
Element title = document.createElement("Title");
title.appendChild(document.createTextNode(mytitle));
root.appendChild(title);
Element content = document.createElement("Content");
content.appendChild(document.createTextNode(mycontent));
root.appendChild(content);
Element price = document.createElement("Price");
price.appendChild(document.createTextNode(myprice));
root.appendChild(price);
}
public void toSave() {
try {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(document);
transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
PrintWriter pw = new PrintWriter(new FileOutputStream(filename));
StreamResult result = new StreamResult(pw);
transformer.transform(source, result);
} catch (TransformerException mye) {
mye.printStackTrace();
} catch (IOException exp) {
exp.printStackTrace();
}
}
public static void main(String args[]) {
try {
Writexml myxml = new Writexml("f:""test.xml");
myxml.toWrite("中文题目", "中文内容呵呵", "jiangtao");
myxml.toSave();
System.out.print("Your writing is successful.");
} catch (ParserConfigurationException exp) {
exp.printStackTrace();
System.out.print("Your writing is failed.");
}
}
}
基本能满足我的小小要求,关键代码段是:
public void toSave() {
try {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(document);
transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
PrintWriter pw = new PrintWriter(new FileOutputStream(filename));
StreamResult result = new StreamResult(pw);
transformer.transform(source, result);
} catch (TransformerException mye) {
mye.printStackTrace();
} catch (IOException exp) {
exp.printStackTrace();
}
}
Ok,在此谢谢作者johnstom了。
转载网址:http://blog.csdn.net/yzj_000/archive/2007/03/22/1537679.aspx