XML.Java document 创建XML

前端之家收集整理的这篇文章主要介绍了XML.Java document 创建XML前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


http://blog.sina.com.cn/s/blog_495697e60100gp6a.html

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
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.Document;
import org.w3c.dom.Element;

public class Test {
 
 public static Document createDocument() throws ParserConfigurationException
 {
  DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  Document document = db.newDocument();
  Element root = document.createElement_x("pictrue");
  Element name = document.createElement_x("name");
  name.setAttribute("attr1","val1");
  name.appendChild(document.createTextNode("pictrue"));
  root.appendChild(name);
  document.appendChild(root);

  return document;
 }
 
 public static void doc2XmlFile(Document document,String filename) throws TransformerException
 {
     TransformerFactory tFactory = TransformerFactory.newInstance();
     Transformer transformer = tFactory.newTransformer();
    
     transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
     DOMSource source = new DOMSource(document);
     StreamResult result = new StreamResult(new File(filename));
     transformer.transform(source,result);
 }


 
 public static void main(String[] args)
 {
  try
  {
   doc2XmlFile(createDocument(),"d:/test.xml");
  } catch (TransformerException e)
  {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (ParserConfigurationException e)
  {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

}

猜你在找的XML相关文章