public XmlBean() { } /** * 读取XML文件所有信息 */ public Vector LoadXML(String path) throws Exception { Vector xmlVector = null; FileInputStream fi = null; try { fi = new FileInputStream(path); xmlVector = new Vector(); SAXBuilder sb = new SAXBuilder(); Document doc = sb.build(fi); Element root = doc.getRootElement(); // 得到根元素 List books = root.getChildren(); // 得到根元素所有子元素的集合 Element book = null; XmlBean xml = null; for (int i = 0; i < books.size(); i++) { xml = new XmlBean(); book = (Element) books.get(i); // 得到第一本书元素 xml.setbookname(book.getChild("书名").getText()); xml.setauthor(book.getChild("作者").getText()); xml.setpub(book.getChild("出版社").getText()); xml.setprice(book.getChild("价格").getText()); xml.setpubdate(book.getChild("出版日期").getText()); xmlVector.add(xml); } } catch (Exception e) { System.err.println(e + "error"); } finally { try { fi.close(); } catch (Exception e) { e.printStackTrace(); } } return xmlVector; } /** * 删除XML文件指定信息 */ public static void DelXML(HttpServletRequest request) throws Exception { FileInputStream fi = null; FileOutputStream fo = null; try { request.setCharacterEncoding("GBK"); String path = request.getParameter("path"); int xmlid = Integer.parseInt(request.getParameter("id")); fi = new FileInputStream(path); SAXBuilder sb = new SAXBuilder(); Document doc = sb.build(fi); Element root = doc.getRootElement(); // 得到根元素 List books = root.getChildren(); // 得到根元素所有子元素的集合 books.remove(xmlid);// 删除指定位置的子元素 // String indent = " "; // boolean newLines = true; // XMLOutputter outp = new XMLOutputter(indent, newLines, "GBK"); Format format = Format.getPrettyFormat(); format.setIndent(" "); format.setEncoding("utf-8"); XMLOutputter outp = new XMLOutputter(format); fo = new FileOutputStream(path); outp.output(doc, fo); } catch (Exception e) { System.err.println(e + "error"); } finally { try { fi.close(); fo.close(); } catch (Exception e) { e.printStackTrace(); } } } |