1.使用Document创建XML文档:
注意:导包时导入org.w3c.dom的包:
创建图书列表:
Book book1 = new Book(1, "001", "魔戒");
book1.addAuthor("托尔金");
Book book2 = new Book(2, "002", "哈利波特");
book2.addAuthor("JK 罗琳");
Book book3 = new Book(3, "004", "冰与火之歌");
book3.addAuthor("乔治马丁");
Book book4 = new Book(4, "009", "三体");
book4.addAuthor("刘慈欣");
book4.addAuthor("杨宇昆");
List list = new ArrayList<>();
list.add(book1);
list.add(book2);
list.add(book3);
list.add(book4);
使用Document创建XML文档:
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element bookList = doc.createElement("book-list");
for (Book b : list) {
Element book = doc.createElement("book");
Attr attr = doc.createAttribute("id");
attr.setValue(String.valueOf(b.getId()));
//为Book标签添加属性ID
book.setAttributeNode(attr);
Element title = doc.createElement("title");
title.appendChild(doc.createTextNode(b.getTitle()));
Element isbn = doc.createElement("isbn");
isbn.appendChild(doc.createTextNode(b.getIsbn()));
Element authorList = doc.createElement("author-list");