package kr.co.swh.lecture.opensource.dom4j; 

import java.io.InputStream;
import java.net.MalformedURLException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * <pre>
 * kr.co.swh.lecture.opensource.dom4j 
 * Dom4jMain.java
 *
 * 설명 : Dom4j
 * </pre>
 * 
 * @since : 2019. 4. 2.
 * @author : tobby48
 * @version : v1.0
 */
public class Dom4jMain {

	public Document createDocument() {
        Document doc = DocumentHelper.createDocument();
        Element root = doc.addElement("students");
        root.addElement("student")
            .addAttribute("name", "yuki")
            .addAttribute("age", "18")
            .addText("cat");

        root.addElement("student")
            .addAttribute("name", "swh")
            .addAttribute("age", "5")
            .addText("academy");

        return doc;
    }
	
	public Document parse(InputStream is) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document doc = reader.read(is);
        return doc;
    }
	
	public static void main(String[] args) throws MalformedURLException, DocumentException {
		Dom4jMain xml = new Dom4jMain();
		@SuppressWarnings("static-access")
		InputStream is = Thread.currentThread().getContextClassLoader().getSystemResourceAsStream("xml.xml");
		Document doc = xml.parse(is);
		String text = doc.asXML();					//	Xml -> String
		System.out.println(text);
		doc = DocumentHelper.parseText(text);		//	String -> Xml
		text = doc.asXML();
		System.out.println(text);
		doc = xml.createDocument();
		text = doc.asXML();
		System.out.println(text);
	}
}