红尘客栈

导航

Java_DOM创建XML

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
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.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class CreateXML {
public static void main(String[] args) {
try {
//获取DOM工厂解析类
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document document=builder.newDocument();
//设置根节点
Element root=document.createElement("Persons");
root.setAttribute("start", "tab");
Element person=document.createElement("person");
person.setAttribute("id", "1");
Element name=document.createElement("name");
name.setTextContent("xiaosan");
Element age=document.createElement("age");
age.setTextContent("100");

//一层一层添加子节点
person.appendChild(name);
person.appendChild(age);
root.appendChild(person);
document.appendChild(root);
System.out.println("xml创建成功!");

//将生成的Document生成file
TransformerFactory transformerFactory=TransformerFactory.newInstance();
Transformer transformer=transformerFactory.newTransformer();

//将xml转换为file文件
transformer.transform(new DOMSource(document),new StreamResult(new FileOutputStream("test.xml")));

//输出到控制台
StringWriter writer=new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(writer));
System.out.println(writer.toString());

//获取xml文件生成Document对象
DocumentBuilderFactory xBuilderFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder=xBuilderFactory.newDocumentBuilder();
Document doc=dBuilder.parse(new InputSource(new FileInputStream("test.xml")));

//More....


} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

}

posted on 2016-06-07 22:08  红尘笔记  阅读(462)  评论(0编辑  收藏  举报