티스토리 뷰

자체 지원되는 클래스를 이용하여 아래와 같은 XML 화일을 생성하는 예제

test.xml


    
        
        
        
        
        
        
    

Hks003.java
import org.w3c.dom.Document;
import org.w3c.dom.Element; import com.sun.org.apache.xerces.internal.dom.DocumentImpl;
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import java.io.*; public class Hks003 {
    private Document doc;
    public void WriteUTF(String fileName)
    {
        try
        {
            FileOutputStream fileoutputstream = new FileOutputStream(new File(fileName));
            OutputFormat outputformat = new OutputFormat();
            //outputformat.setEncoding("UTF-8");
            outputformat.setIndent(4);
            outputformat.setIndenting(true);
            outputformat.setPreserveSpace(false);             
            
            XMLSerializer serializer = new XMLSerializer();
            serializer.setOutputFormat(outputformat);
            serializer.setOutputByteStream(fileoutputstream);
            serializer.asDOMSerializer();
            serializer.serialize(doc.getDocumentElement());             
           
            StringWriter  stringOut = new StringWriter();
            XMLSerializer    str_serial = new XMLSerializer( stringOut, outputformat );
            str_serial.asDOMSerializer();
            str_serial.serialize( doc.getDocumentElement() );            
            System.out.println(stringOut.toString());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    
    Hks003 ()
    {
        try
        {
            doc = new DocumentImpl();
            Element root = doc.createElement("XMLROOT");
            Element record = doc.createElement("RECORD");
            
           Element pname = doc.createElement("PNAME");
           Element webip = doc.createElement("WEBIP");
           webip.setAttribute("type", "localhost");
           Element dbip = doc.createElement("DBIP");
           dbip.setAttribute("type", "localhost");
           Element dbname = doc.createElement("DBNAME");
           dbname.setAttribute("type", "watercomdb");
           Element dbid = doc.createElement("DBID");
           dbid.setAttribute("type", "root");
           Element dbpass = doc.createElement("DBPASS");
           dbpass.setAttribute("type", "kmec");
   
           root.appendChild(record);            
           record.appendChild(pname);
           record.appendChild(webip);
           record.appendChild(dbip);
           record.appendChild(dbname);
           record.appendChild(dbid);
           record.appendChild(dbpass);
            
           doc.appendChild(root);
           WriteUTF("c:\\test.xml");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    } 
    public static void main(String[] args)
    {
        new Hks003();
    }
}
좀 복잡하죠! 역시 라이브러리를 사용하는 것이... ^^