flowers.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<flowers>
<flower id="1">
<name>玫瑰</name>
<price>10</price>
</flower>
<flower id="2">
<name>百合</name>
<price>20</price>
</flower>
<flower id="3">
<name>兰花</name>
<price>30</price>
</flower>
</flowers>
WriteXML.java文件
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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;
public class WriteXML {
public static void main(String[] args) throws Exception{
//载入flowers.xml文件
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
Document doc=db.parse("flowers.xml");
//保存文件
TransformerFactory tf=TransformerFactory.newInstance();
Transformer transformer=tf.newTransformer();
DOMSource source=new DOMSource(doc); //将Document对象封装为DOM源
File file=new File("newFlowers.xml");
StreamResult result=new StreamResult(file); //通过StreamResult包装File对象,确定输出的目标
transformer.transform(source, result); //利用Transformer的transform方法将源输出到目标
System.out.println("保存成功!!");
}
}
![](http://static.oschina.net/uploads/space/2012/0406/190502_9J3b_137892.jpg)