创建xml并初始化

 

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Iterator;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
public class writeXML
{

public static void callWriteXmlFile(Document doc, Writer w,
             String encoding) {
try {
Source source = new DOMSource(doc);

Result result = new StreamResult(w);

Transformer xformer = TransformerFactory.newInstance()
.newTransformer();
xformer.setOutputProperty(OutputKeys.ENCODING, encoding);
xformer.transform(source, result);

}
catch (TransformerConfigurationException e) {
e.printStackTrace();
}
catch (TransformerException e) {
e.printStackTrace();
}
}

private void writeXMLFile(String outfile)
{
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder=null;
    try
    {
    builder = dbf.newDocumentBuilder();
    }
    catch(Exception e){}
    Document doc = builder.newDocument();
 
    Element root = doc.createElement_x_x("学生花名册");
    doc.appendChild(root); //将根元素添加到文档上
 
    //获取学生信息
     //创建一个学生
     Element stu = doc.createElement_x_x("学生");
     stu.setAttribute("性别","男");
     root.appendChild(stu);//添加属性
  
     //创建文本年龄节点
     Element age = doc.createElement_x_x("年龄");
     stu.appendChild(age); //将age添加到学生节点上
     Text tage = doc.createTextNode("23");
     age.appendChild(tage); //将文本节点放在age节点上
  
     //创建文本姓名节点
     Element name = doc.createElement_x_x("姓名");
     stu.appendChild(name);
     Text tname = doc.createTextNode("灰太郎");
     name.appendChild(tname);
    try {
     FileOutputStream fos = new FileOutputStream(outfile);
     OutputStreamWriter outwriter = new OutputStreamWriter(fos);
     //((XmlDocument)doc).write(outwriter); //出错!
     callWriteXmlFile(doc,outwriter,"gb2312");
     outwriter.close();
     fos.close();
    } catch (Exception e) {
     e.printStackTrace();
    }
}
public static void main(String args[])
{
    writeXML w = new writeXML();
    String outfile = "D:/student.txt";
    w.writeXMLFile(outfile);

  }
    
}

上述方法可用于XML文档的初始化。
文章转载自http://blog.sina.com.cn/s/blog_49b05ad00100gcka.html

你可能感兴趣的:(xml)