论坛首页 入门技术论坛

XML 文件的操作(七)

浏览 1997 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-01-08  
package com.ibm.xml;

import java.io.FileWriter;
import java.io.IOException;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

/**
 * DOM4J写文件
 * @author Administrator
 *
 */
public class Dom4jTest
{

	
	public static void main(String[] args)
	{
		Document doc=DocumentHelper.createDocument();
		
		doc.addProcessingInstruction("xml-stylesheet","type='text/xsl' href='students.xsl'");
		
		Element root=doc.addElement("students");
		
		Element eltStu1=root.addElement("student");
		Element eltName1=eltStu1.addElement("name");
		Element eltAge1=eltStu1.addElement("age");
		
		eltName1.setText("张三");
		eltAge1.setText("18");
		
		Element eltStu2=root.addElement("student");
		Element eltName2=eltStu2.addElement("name");
		Element eltAge2=eltStu2.addElement("age");
		
		eltName2.setText("李四");
		eltAge2.setText("20");
		
		//PrintWriter pw=new PrintWriter(System.out);
		OutputFormat outFmt=new OutputFormat("    ",true);
		outFmt.setEncoding("gb2312");
		
		
		try
		{
			XMLWriter xmlWriter=new XMLWriter(new FileWriter("dom4jtest.xml"),outFmt);
			xmlWriter.write(doc);
			xmlWriter.close();
		}
		catch (IOException e)
		{
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}
	}

}
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics