DOM生成xml文件或xml字符串

package com.example.study.TestMybatisQuery.util;

 

import java.io.ByteArrayOutputStream;

 

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 GenerateXML {

 

public static String createXML() throws Exception{

 

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

 

DocumentBuilder builder = factory.newDocumentBuilder();

 

Document document = builder.newDocument();

 

Element bookstore = document.createElement("bookstore");

 

Element book = document.createElement("book");

book.setAttribute("id", "1");

 

// 为book添加子节点

Element name = document.createElement("name");

name.setTextContent("安徒生童话");

book.appendChild(name);

Element author = document.createElement("author");

author.setTextContent("安徒生");

book.appendChild(author);

Element price = document.createElement("price");

price.setTextContent("49");

book.appendChild(price);

 

bookstore.appendChild(book);

 

document.appendChild(bookstore);

 

document.setXmlStandalone(true);

 

TransformerFactory tff = TransformerFactory.newInstance();

 

Transformer tf = tff.newTransformer();

 

tf.setOutputProperty(OutputKeys.INDENT, "yes");

 

tf.transform(new DOMSource(document), new StreamResult("c:/xmlfile.xml"));//生成xml文件

 // xml transform String  

        ByteArrayOutputStream bos = new ByteArrayOutputStream();  

        tf.transform(new DOMSource(document), new StreamResult(bos));  //生成xml字符串

        String xmlString = bos.toString();  

        System.out.println(xmlString);

return xmlString;

}

public static void main(String[] args) {

try {

 createXML();

} catch (Exception e) {

e.printStackTrace();

}

}

}

你可能感兴趣的:(java基础部分)