import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class BookUtis { public List<Book> xmlToBook(InputStream is) throws Exception{ //封装了对xml的解析 SAXReader read=new SAXReader(); //做文件,解析器读取数据InputStream。从网络端收取数据或者从文件中读取数据 Document doc=read.read(is); //根元素 Element root=doc.getRootElement(); List<Book> booklist=new ArrayList<Book>(); List<Element> bookElements=root.elements("book");//这个文件万一下面有多个子元素的话,只拿其中book for(Element e:bookElements){ Book book=new Book(); //明确book下只有name单个元素 // book元素下获取name返回Element类型的list,只有一个元素取get(0)获取第一行,整体扩起来是一个单个元素,获取文本,tostring String name=((Element)(e.elements("name").get(0))).getData().toString(); double price=Double.parseDouble(((Element)(e.elements("price").get(0))).getData().toString()); book.setName(name); book.setPrice(price); booklist.add(book); } return booklist; } public List<Book> xmlToBook(String xmlFileName) throws Exception{ InputStream is=new FileInputStream(xmlFileName); List<Book> list=xmlToBook(is); return list; } public void bookToXML(List<Book> booklist,OutputStream os) throws Exception{ Document doc=DocumentHelper.createDocument(); Element root=doc.addElement("books"); for(Book book:booklist){ Element bookElement=root.addElement("book"); bookElement.addElement("name").setText(book.getName()); bookElement.addElement("price").setText(String.valueOf(book.getPrice())); } XMLWriter write=new XMLWriter(os,OutputFormat.createCompactFormat()); write.write(doc); write.close(); } }