JAVA如何写XML文件
不需要去读。只需要去写XML。已经从数据库中读出来数据了,如果把数据写成XML格式。我用的是DOM4J。但是不会写。请说的详细点。最好做个简单的例子。越简单容易理解越好。...
不需要去读。只需要去写XML。已经从数据库中读出来数据了,如果把数据写成XML格式。我用的是DOM4J。但是不会写。请说的详细点。最好做个简单的例子。越简单容易理解越好。
展开
2个回答
展开全部
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();
}
}
}
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();
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询