xml文件的创建

package com.jxufe.read;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
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 XMLDOMWriter {

	public static void main(String[] args) {
		//创建一个DocumentBuilderFactory对象
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
        	//利用DocumentBuilderFactory对象创建一个DocumentBuilder对象
			DocumentBuilder builder = factory.newDocumentBuilder();
			//创建一个根节点,这是我的理解。
			Document document = builder.newDocument();
			Element element = document.createElement("world");
			Element person = document.createElement("person");
			person.setAttribute("id", "1");
			 /**
		     * 添加姓名到person节点里面
		     */
		    Element name = document.createElement("name");
		      name.setTextContent("张三");
		    person.appendChild(name);
		    /**
		     * 添加年龄到person节点里面
		     */
		    Element age = document.createElement("age");
		    age.setTextContent("23");
		    person.appendChild(age);
		    //把person节点添加到World 节点里面
			element.appendChild(person);
			//把World节点添加到根节点 节点里面
			document.appendChild(element);
			
			TransformerFactory factory1 = TransformerFactory.newInstance();
			Transformer transformer = factory1.newTransformer();
			//实现换行
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		    transformer.transform(new DOMSource(document), new StreamResult("1.xml"));
			
		} catch (Exception e) {
			throw new RuntimeException("写入XML文件失败",e);
		}
	}
}

结果:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<world>
<person id="1">
<name>张三</name>
<age>23</age>
</person>
</world>


你可能感兴趣的:(xml文件的创建)