1. 如果要將讀取的XML文件,再寫入另外的一個(gè)新XML文件中,首先必須新建一個(gè)和要讀取相對(duì)應(yīng)的beans類,通過set方法填充數(shù)據(jù),get方法獲取數(shù)據(jù)。
2. 在讀取XML文件的時(shí)候,需要用到ArrayList集合來存儲(chǔ)每次從原XML文件里面讀取的數(shù)據(jù),在寫入新的XML文件的時(shí)候,也要通過ArrayList集合獲取要遍歷的次數(shù),同時(shí)將數(shù)據(jù)寫入到新的xml文件中
3. 詳細(xì)代碼如下:
public static void main(String[] args) {
try {
String url = "book.xml";
ArrayList list = getBookList(url);
//寫入一個(gè)新的xml文件
FileWriter fw = new FileWriter("newbook.xml");
fw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
fw.write("\n<books>");
for (int i = 0; i < list.size(); i++) {
BookBean book = (BookBean)list.get(i);
fw.write("\n<book>\n");
if(book.getTitle()!=null){
fw.write("<title>");
fw.write(book.getTitle());
fw.write("</title>\n");
}
if(book.getAuthor()!=null){
fw.write("<author>");
fw.write(book.getAuthor());
fw.write("</author>\n");
}
if(book.getPrice()!=null){
fw.write("<price>");
fw.write(book.getPrice());
fw.write("</price>\n");
}
fw.write("</book>\n");
}
fw.write("</books>");
fw.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
//獲取從一個(gè)xml文件中讀取的數(shù)據(jù),并將其保存在ArrayList中
public static ArrayList getBookList(String url){
ArrayList list = new ArrayList();
try{
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(url);
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();
BookBean book = new BookBean();
book.setTitle(title);
book.setAuthor(author);
book.setPrice(price);
list.add(book);
}
}catch(Exception e){
System.out.println(e.getMessage());
}
return list;
}
}
如果你想把這個(gè)代碼看懂的話,我建議你,先把怎樣從XML讀取的數(shù)據(jù)的看懂!
posted on 2009-03-16 07:34
Werther 閱讀(3077)
評(píng)論(1) 編輯 收藏 所屬分類:
10.Java