[教學]Java-產生標準的XML File

如果你願意,利用兜字申也能產生XML File,不過如果資料來源很亂的話,

應該也是個麻煩,以下是一個利用java 標準的Framework

package file;

import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
 
public class CreateXML {
  public static void main(String[] args) throws Exception {

    String[] data={"123","456","789","135"};//資料
    String[] elmName={"el","el","el","el"};//資料的Element Name
   
 
    String root ="root";
    DocumentBuilderFactory documentBuilderFactory =
                        DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder =
                              documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();
    Element rootElement = document.createElement(root);
        document.appendChild(rootElement);
    for (int i = 1; i < data.length; i++){//建立xml
      Element em = document.createElement(elmName[i]);
      em.appendChild(document.createTextNode(data[i]));
      rootElement.appendChild(em);
    }
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(document);
        StreamResult result =  new StreamResult(System.out);
        transformer.transform(source, result);
  }
}

有興趣的人可以拿來試看看^^

發表迴響