在Java中读取写入XML文件(DEMO_004)
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读取的数据的看懂!