2013年7月11日 星期四

java write xml

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
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 java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class createxml {

    public static void main(String argv[]) {

Run ();} public static void Run() {

    Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");// 設定日期格式
        String dateString = sdf.format(date);
        String filename="spooled" + dateString + ".xml";
        File docFile = new File(filename);

      try {

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("datafeed");
        doc.appendChild(rootElement);

        // staff elements
        Element staff = doc.createElement("package");
        rootElement.appendChild(staff);

        // set attribute to staff element
        Attr attr = doc.createAttribute("id");
        attr.setValue(" ");
        staff.setAttributeNode(attr);

        // shorten way
        // staff.setAttribute("id", "1");

        // firstname elements
        Element firstname = doc.createElement("P");
        firstname.appendChild(doc.createTextNode("0"));
        staff.appendChild(firstname);

        // lastname elements
        Element lastname = doc.createElement("M");
        lastname.appendChild(doc.createTextNode("0"));
        staff.appendChild(lastname);

        // nickname elements
        Element nickname = doc.createElement("F");
        nickname.appendChild(doc.createTextNode("init"));
        staff.appendChild(nickname);

        // salary elements
        Element salary = doc.createElement("S");
        salary.appendChild(doc.createTextNode(""));
        staff.appendChild(salary);

        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);

        StreamResult result = new StreamResult(new File(filename));

        transformer.transform(source, result);

        System.out.println("File " +filename + " created!");

      } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
      } catch (TransformerException tfe) {
        tfe.printStackTrace();
      }
    }
}

沒有留言:

張貼留言