import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
/**
* @开发人员: 死胖子
* 2009 1:32:41 PM
*/
public class XMLToNewXml {
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
String uri="book.xml";
String path="D:/newbook.xml";
ArrayList list=getBookList(uri);
OutputStreamWriter fs = new OutputStreamWriter(new FileOutputStream(path),"UTF-8");
fs.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
fs.write("\n<books>");
for(int i=0;i<list.size();i++){
Book book=(Book)list.get(i);
fs.write("\n<book>\n");
if(book.getTitle()!=null){
fs.write("<title>");
fs.write(book.getTitle());
fs.write("</title>\n");
}
if(book.getAuthor()!=null){
fs.write("<author>");
fs.write(book.getAuthor());
fs.write("</author>\n");
}
if(book.getPrice()!=null){
fs.write("<price>");
fs.write(book.getPrice());
fs.write("</price>");
}
fs.write("\n</book>\n");
}
fs.write("</books>");
fs.flush();
fs.close();
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
}
public static ArrayList getBookList(String uri){
ArrayList list=new ArrayList();
try{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
Document doc=db.parse(uri);
NodeList nodeList=doc.getElementsByTagName("book");
for(int i=0;i<nodeList.getLength();i++){
String title=doc.getElementsByTagName("title").item(i).getFirstChild().getNodeValue();
String author=doc.getElementsByTagName("author").item(i).getFirstChild().getNodeValue();
String price=doc.getElementsByTagName("price").item(i).getFirstChild().getNodeValue();
Book book=new Book();
book.setTitle(title);
book.setAuthor(author);
book.setPrice(price);
list.add(book);
}
}catch(Exception e){
System.out.println(e.getMessage());
}
return list;
}
}
自己想做了一个小例子!学习ING、、、、、希望给大家带来帮助