w3c xml 생성 변경 코드

작업중 필요없어져서 삭제하려다가 저장

Xml 이용해서 정보 저장하는코드.  오브젝트 네임을 바꿨는데 이 과정에서 오류가 약간 있을수도..

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

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.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;


public class SchoolDao {

	private final Document document;
	private final Node root;
	private final File file;

	public SchoolDao() throws ParserConfigurationException, FileNotFoundException, SAXException, IOException {
		this("conf", "server.xml");
	}
	public SchoolDao(String filePath, String fileName) throws ParserConfigurationException, FileNotFoundException, SAXException, IOException {
		file = new File(filePath, fileName);
		if (file.exists() && file.isFile()) {
			document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new FileInputStream(file));
			root = document.getFirstChild();
		} else {
			document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
			root = document.createElement("root");
			document.appendChild(root);
			new File(filePath).mkdirs();
			file.createNewFile();
		}
	}

	public void addSchool(SchoolObject so) {
		Node school = document.createElement("server");

		addNode(school, "name", so.getName());
		addNode(school, "score", so.getScore());
		
		root.appendChild(school);
	}
	
	private void addNode(Node parent, String nodeName, String nodeContent){
		Node tmpNode;
//		Attr tmpAttr;
		tmpNode = document.createElement(nodeName);
		tmpNode.setTextContent(nodeContent);
//		((Element)tmpNode).setAttributeNode(tmpAttr);
		parent.appendChild(tmpNode);
	}

	public void write() throws TransformerException {
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(document);
		StreamResult result = new StreamResult(file);
		transformer.transform(source, result);
		// Output to console for testing
		StreamResult consoleResult = new StreamResult(System.out);
		transformer.transform(source, consoleResult);
	}

	public static void main(String[] args) throws FileNotFoundException, ParserConfigurationException, SAXException,
			IOException, TransformerException {
		SchoolDao dao = new SchoolDao();
		SchoolObject so = new SchoolObject("schoolname");
		so.setScore(100);
		dao.addHost(so);
		dao.write();
	}
}

 

Leave a Reply

Your email address will not be published.

 characters available