1.如果要將讀取的XML文件,再寫入另外的一個新XML文件中,首先必須新建一個和要讀取相對應的beans類,通過set方法填充數據,get方法獲取數據。
2.在讀取XML文件的時候,需要用到ArrayList集合來存儲每次從原XML文件裡面讀取的數據,在寫入新的XML文件的時候,也要通過ArrayList集合獲取要遍歷的次數,同時將數據寫入到新的xml文件中
3.詳細代碼如下:
public static void main(String[] args) { try { String url = "book.xml"; ArrayList list = getBookList(url); //寫入一個新的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()); } }
//獲取從一個xml文件中讀取的數據,並將其保存在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; } }
如果你想把這個代碼看懂的話,我建議你,先把怎樣從XML讀取的數據的看懂!