package com.itjob.xml;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * 第7章 Java XML编程
 * 考题：使用JDOM的API进行编程，要求在D盘的people.xml文件写入如下内容：
*  <?xml version="1.0" encoding="GB2312"?>
*  <老师>
*      <问候语>我是谢老师</问候语>
*  </老师>
*  注意：该xml文件中有中文，需要解决中文乱码问题。
 * @author AmigoXie
 */
public class JDOMTest {
	public static void main(String args[]) {
		String outFile = "D:\\people.xml";
		try {
			DocumentBuilder builder = DocumentBuilderFactory.newInstance()
					.newDocumentBuilder();
			Document doc = builder.newDocument();
			Element root = doc.createElement("老师");
			Element greeting = doc.createElement("问候语");
			greeting.appendChild(doc.createTextNode("我是谢老师"));
			root.appendChild(greeting);
			doc.appendChild(root);
			Transformer transformer = javax.xml.transform.TransformerFactory
					.newInstance().newTransformer();
			transformer.setOutputProperty(OutputKeys.ENCODING, "gb2312");
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");

			transformer.transform(new DOMSource(doc),new StreamResult(outFile));
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
}
