首页 > 代码库 > javaxml文件基础:Dom怎么生成xml文件

javaxml文件基础:Dom怎么生成xml文件

package CreateXmlByDom;import java.io.File;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import javax.xml.transform.Result;import javax.xml.transform.Source;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;public class testCom {	public static void main(String[] args) throws Exception{		//1:第一步获取DocumentBuilderFactory对象			DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();		//2:获取一个DocumentBuilder对象			DocumentBuilder db= factory.newDocumentBuilder();		//3:创建一个Document类型的空文档				Document doc=db.newDocument();		//4:创建doc文档中的根节点bookstore				Element bookstore=doc.createElement("bookstore");		//5:创建一个bookstore节点的子节点book				Element book=doc.createElement("book");		//6:为book节点设置属性				book.setAttribute("id	", "1");		//7:为book设置文本内容,包括四个文本内容,name,  author,price ,version				Element name=doc.createElement("name");//继续设定一个孙节点				name.setTextContent("Core java");				Element author=doc.createElement("author");//继续设定一个孙节点				author.setTextContent("Horstmann");				Element price=doc.createElement("price");//继续设定一个孙节点				price.setTextContent("36");				Element version=doc.createElement("version");//继续设定一个孙节点				version.setTextContent("4.0");		//8:同时的将创建的bookstore 节点添加到doc文件中去				doc.appendChild(bookstore);		//9:将book节点添加到bookstore节点中去				bookstore.appendChild(book);		//10:将name,author,price ,version 等文本添加到book节点中去				book.appendChild(name);				book.appendChild(author);				book.appendChild(price);				book.appendChild(version);		//11:获得TransformerFactory对象,并且通过newInstance()方法实例化TransformerFactory对象				TransformerFactory transformerfactory=TransformerFactory.newInstance();//工厂类		//12:获得Transformer对象,注意这里面的transform的方法
// transformer.transform(new DOMSource(doc), new StreamResult(new File("bookstore.xml"))); 
 
             Transformer transformer=transformerfactory.newTransformer(); 


            Source xmlsource=new DOMSource(doc);
            Result outputTarget = new StreamResult(new File("bookstore1.xml"));
            transformer.transform(xmlsource, outputTarget); } }

  

javaxml文件基础:Dom怎么生成xml文件