67,512
社区成员
发帖
与我相关
我的任务
分享
public class Book {
private String name;
private String author;
public Book(String name, String author) {
this.name = name;
this.author = author;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
public class CreateXmlByList {
public static void main(String[] args) {
List<Book> bookList = new ArrayList<Book>();
bookList.add(new Book("三国演义", "罗贯中"));
bookList.add(new Book("水浒传", "施耐庵"));
bookList.add(new Book("西游记", "吴承恩"));
bookList.add(new Book("曹雪芹", "高鄂"));
Document d = DocumentHelper.createDocument();
//创建根节点
Element books = d.addElement("books");
for (Book book : bookList) {
Element bookElement = books.addElement("book");
bookElement.addElement("name").addText(book.getName());
bookElement.addElement("author").addText(book.getAuthor());
}
d.setXMLEncoding("utf-8");
System.out.println("生成的xml文件是:");
System.out.print(d.asXML());
}
}