Java操作XML文件(1)-写入XML文件

package xml;  
  
import java.io.BufferedWriter;  
import java.io.FileOutputStream;  
import java.io.OutputStreamWriter;  
  
import javax.xml.parsers.DocumentBuilder;  
import javax.xml.parsers.DocumentBuilderFactory;  
import javax.xml.transform.OutputKeys;  
import javax.xml.transform.Transformer;  
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 XMLWriter {  
    private String fileName;  
    private Document document;  
  
    public XMLWriter(String fileName) throws Exception {  
        this.fileName = fileName;  
        createXmlDocument();  
    }  
  
    private void createXmlDocument() throws Exception {  
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
        DocumentBuilder builder = factory.newDocumentBuilder();  
        document = builder.newDocument();  
    }  
  
    public Element createDocumentElement(String name) {  
        Element root = document.createElement(name);  
        document.appendChild(root);  
        return root;  
    }  
  
    public Element createElement(Element parent, String tagName, String text) {  
        Element element = document.createElement(tagName);  
        if (text != null && text.length() > 0) {  
            element.setTextContent(text);  
        }  
        parent.appendChild(element);  
        return element;  
    }  
  
    public void toSave() throws Exception {  
        TransformerFactory factory = TransformerFactory.newInstance();  
        factory.setAttribute("indent-number", new Integer(4));// 设置缩进长度为4  
        Transformer transformer = factory.newTransformer();  
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");// 设置自动换行  
        DOMSource source = new DOMSource(document);  
        transformer.transform(source, new StreamResult(new BufferedWriter(  
                new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8"))));  
    }  
  
    public static void main(String[] args) {  
        String fileName = "E:\\test.xml";  
        System.out.println(fileName);  
        try {  
            XMLWriter writer = new XMLWriter(fileName);  
            Element root = writer.createDocumentElement("Books");  
            Element book = writer.createElement(root, "Book", "");  
            writer.createElement(book, "Price", "52.00");  
            Element title = writer.createElement(book, "Title", "test xml");  
            title.setAttribute("Auth", "yy");  
            writer.toSave();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
}  

你可能感兴趣的:(java,xml,文件读写)