JAVA如何写XML文件?
发布网友
发布时间:2022-05-05 15:10
我来回答
共2个回答
热心网友
时间:2022-06-27 16:09
import java.io.*;
import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
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").addAttribute("sn", "01");
Element eltName1 = eltStu1.addElement("name");
Element eltAge1 = eltStu1.addElement("age");
eltName1.setText("张三");
eltAge1.setText("20");
Element eltStu2 = root.addElement("student").addAttribute("sn", "02");
Element eltName2 = eltStu2.addElement("name");
Element eltAge2 = eltStu2.addElement("age");
eltName2.setText("李四");
eltAge2.setText("18");
try {
OutputFormat format = new OutputFormat("
", true);
format.setEncoding("gb2312");
// 可以把System.out改为你要的流。
XMLWriter xmlWriter = new XMLWriter(new PrintWriter(System.out), format);
xmlWriter.write(doc);
xmlWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
热心网友
时间:2022-06-27 16:10
呵呵,你这个问题,其实写XML很简单的,氛围以下几步:
1.导入DOM4J包,在此我使用dom4j来做。
2.创建dom4j的实例:Document document = DocumentHelper.createDocument();
3.一级一级的添加节点或者属性,这个具体参照dom4j帮助:
Element rootGen = document.addElement("root");
4.定义以下3个对象,然后进行操作:
Writer writer = null;
OutputFormat format = null;
XMLWriter xmlwriter = null;
***********************************************************************************
附上代码:
public void CreateXMl(StudentBean sn){
//创建document对象
Document document = DocumentHelper.createDocument();
//定义根节点Element
Element rootGen = document.addElement("root");
//定义根节点ROOT的子节点们
Element nameGen = rootGen.addElement("Name");
nameGen.addAttribute("name", "我是中文");
Element ageGen = rootGen.addElement("Age");
Element addrGen = rootGen.addElement("Address");
Writer writer = null;
OutputFormat format = null;
XMLWriter xmlwriter = null;
//将定义好的内容写入xml文件中
try {
//使用这个writer也可以,只不过遇到中文会乱码哦
// writer = new FileWriter("d:/test.xml");
//进行格式化
format = OutputFormat.createPrettyPrint();
//设定编码
format.setEncoding("UTF-8");
xmlwriter = new XMLWriter(new FileOutputStream("d:/test.xml"), format);
xmlwriter.write(document);
xmlwriter.flush();
xmlwriter.close();
System.out.println("-----------Xmlfile successfully created-------------");
} catch (Exception e) {
e.printStackTrace();
System.out.println("-----------Exception occured ring of create xmlfile -------");
}
}