通过将上一篇的更改,将Java对象映射到xml文件中扩展性增强!
1、想看两个简单的实体类
public class FriendsInfo extends BasePojo{ String name ; String gtalk; String address; String image; String QQ; String MSN; public FriendsInfo(String name, String address) { this.address =address; this.name = name; } public FriendsInfo() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGtalk() { return gtalk; } public void setGtalk(String gtalk) { this.gtalk = gtalk; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getQQ() { return QQ; } public void setQQ(String qQ) { QQ = qQ; } public String getMSN() { return MSN; } public void setMSN(String mSN) { MSN = mSN; } }
public class BookInfo extends BasePojo{ String name = ""; String title = ""; String context =""; String price = ""; String show = ""; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContext() { return context; } public void setContext(String context) { this.context = context; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getShow() { return show; } public void setShow(String show) { this.show = show; }
2、两个实体类的父类
public class BasePojo { }
3、处理所需要的介面
public interface DOMExecute { public void addInfo(BasePojo basepojo); public void delInfo(BasePojo basepojo); public void changeInfo(BasePojo basepojo); public List getinfo(); public void createDocument( String dir); }
4、用到的适配器
public class EnumerationAdapter implements Iterator { private Enumeration enumeration; EnumerationAdapter(Enumeration enumeration) { this.enumeration = enumeration; } // 转接介面 public boolean hasNext() { return enumeration.hasMoreElements(); } public Object next() { return enumeration.nextElement(); } public void remove() { } }
5、处理类的父类
public abstract class baseDomHander implements DOMExecute{ ModeDocumentFactory modeDocumentFactory; private String dir = modeDocumentFactory.getDIR(); public baseDomHander(ModeDocumentFactory modeFactory){ modeDocumentFactory = modeFactory; } public ModeDocumentFactory getModeDocumentFactory() { return modeDocumentFactory; } public void setModeDocumentFactory(ModeDocumentFactory modeDocumentFactory) { this.modeDocumentFactory = modeDocumentFactory; } public String getDir() { return dir; } public void setDir(String dir) { this.dir = dir; } public void saveXml(Document document,String dir){ try{ XMLWriter output = null; OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); output = new XMLWriter(new FileWriter(new File(dir)),format); output.write(document); output.close(); }catch(Exception ex){ ex.printStackTrace(); } } public void addEleText(Element el, String text) { if(text!=null) el.addText(text); }
6、Bookinfo的处理类
public class bookDomHander extends baseDomHander{ private String dir ; public bookDomHander(ModeDocumentFactory modeFactory) { super(modeFactory); } @Override public void delInfo(BasePojo basepojo) { BookInfo bi = (BookInfo)basepojo; Document document=null; SAXReader saxReader = new SAXReader(); try{ FileReader fr= new FileReader(new File(getDir())); document = saxReader.read(fr); }catch(Exception e){ e.printStackTrace(); } List list = document.selectNodes("//books/book/name"); Iterator iter = list.iterator(); while(iter.hasNext()){ System.out.print("###########\n"); if(iter.hasNext()){ Element ownerElement = (Element)iter.next(); if(ownerElement.getText().equals(bi.getName())) ownerElement.getParent().getParent().remove(ownerElement.getParent()); } } saveXml(document, getDir()); } @Override public List getinfo() { return null; } @Override public void createDocument( String dir) { setDir(dir); Document document = DocumentHelper.createDocument(); Element books = document.addElement("books"); Element book=books.addElement("book"); Element title=book.addElement("title"); title.addAttribute("show", "yes"); Element context=book.addElement("context"); Element qq=book.addElement("qq"); Element address=book.addElement("price"); try{ XMLWriter output = new XMLWriter( new FileWriter(new File(dir))); output.write( document ); output.close(); } catch(IOException e){System.out.println(e.getMessage()); } saveXml(document, dir); } @Override public void addInfo(BasePojo basepojo) { BookInfo bi = (BookInfo)basepojo; Document document=null; SAXReader saxReader = new SAXReader(); try{ FileReader fr= new FileReader(new File(this.getDir())); document = saxReader.read(fr); }catch(Exception e){ e.printStackTrace(); } Element catalogElement = document.getRootElement(); Element book=catalogElement.addElement("book"); Element name=book.addElement("name"); addEleText(name,bi.getName()); Element title=book.addElement("title"); addEleText(title,bi.getTitle()); Element show = title.addAttribute("show", bi.getShow()); Element context = book.addElement("context"); addEleText(context,bi.getContext()); saveXml(document, this.getDir()); } public String getDir() { return dir; } public void setDir(String dir) { this.dir = dir; } @Override public void changeInfo(BasePojo basepojo) { } }
7、friendinfo的处理类
public class friendDomHander extends baseDomHander{ public friendDomHander(ModeDocumentFactory modeFactory) { super(modeFactory); } public void addInfo(FriendsInfo fi) { org.dom4j.Document document=null; org.dom4j.io.SAXReader saxReader = new org.dom4j.io.SAXReader(); try{ FileReader fr= new FileReader(new File(getDir())); document = saxReader.read(fr); }catch(Exception e){ e.printStackTrace(); } Element catalogElement = document.getRootElement(); Element fmessage=catalogElement.addElement("message"); Element name=fmessage.addElement("name"); addEleText(name,fi.getName()); Element gtalk=fmessage.addElement("gtalk"); addEleText(gtalk,fi.getGtalk()); Element msn=fmessage.addElement("msn"); addEleText(msn,fi.getMSN()); Element qq=fmessage.addElement("qq"); addEleText(qq,fi.getQQ()); Element address=fmessage.addElement("address"); addEleText(address,fi.getAddress()); Element image=fmessage.addElement("image"); addEleText(image,fi.getImage()); saveXml(document, getDir()); } public void changeInfo(BasePojo basepojo){ delInfo(basepojo); addInfo(basepojo); } @Override public void delInfo(BasePojo basepojo) { FriendsInfo fi = (FriendsInfo)basepojo; Document document=null; SAXReader saxReader = new SAXReader(); try{ FileReader fr= new FileReader(new File(getDir())); document = saxReader.read(fr); }catch(Exception e){ e.printStackTrace(); } List list = document.selectNodes("//friends/message/name"); Iterator iter = list.iterator(); while(iter.hasNext()){ System.out.print("###########\n"); if(iter.hasNext()){ Element ownerElement = (Element)iter.next(); if(ownerElement.getText().equals(fi.getName())) ownerElement.getParent().getParent().remove(ownerElement.getParent()); } } saveXml(document, getDir()); } @Override public List getinfo() { return null; } @Override public void createDocument( String dir) { setDir(dir); Document document = DocumentHelper.createDocument(); Element catalogElement = document.addElement("friends"); Element fmessage=catalogElement.addElement("message"); Element image=fmessage.addElement("image"); Element name=fmessage.addElement("name"); Element gtalk=fmessage.addElement("gtalk"); Element msn=fmessage.addElement("msn"); Element qq=fmessage.addElement("qq"); Element address=fmessage.addElement("address"); fmessage=catalogElement.addElement("message"); try{ XMLWriter output = new XMLWriter( new FileWriter(new File(dir))); output.write( document ); output.close(); } catch(IOException e){System.out.println(e.getMessage()); } saveXml(document, dir); } @Override public void addInfo(BasePojo basePojo) { delInfo( basePojo); FriendsInfo fi = (FriendsInfo)basePojo; Document document=null; SAXReader saxReader = new SAXReader(); try{ FileReader fr= new FileReader(new File(this.getDir())); document = saxReader.read(fr); }catch(Exception e){ e.printStackTrace(); } Element catalogElement = document.getRootElement(); Element fmessage=catalogElement.addElement("message"); Element name=fmessage.addElement("name"); addEleText(name,fi.getName()); Element gtalk=fmessage.addElement("gtalk"); addEleText(gtalk,fi.getGtalk()); Element msn=fmessage.addElement("msn"); addEleText(msn,fi.getMSN()); Element qq=fmessage.addElement("qq"); addEleText(qq,fi.getQQ()); Element address=fmessage.addElement("address"); addEleText(address,fi.getAddress()); Element image=fmessage.addElement("image"); addEleText(image,fi.getImage()); saveXml(document, this.getDir()); } }
8、单例工厂
public class ModeDocumentFactory{ public static HashMap<String, baseDomHander> infoClassNameAndHandlerPool ; private static ResourceBundle resource; //默认xml路径 private static String DIR; //处理bean对象到xml的类 private static baseDomHander hander = null; static{ //将bean的classname作为key,处理bean的类作为value infoClassNameAndHandlerPool = new HashMap<String, baseDomHander>(); } public static ModeDocumentFactory instance = null; // private ThreadLocal perThreadCacheDir = new ThreadLocal(); private ModeDocumentFactory(){ try { init(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static ModeDocumentFactory getInstance(){ if(instance != null ){ return instance; }else{ instance = new ModeDocumentFactory(); } return instance; } private void init() throws InstantiationException, IllegalAccessException, ClassNotFoundException{ //获得配置文件对应的key -- value resource = ResourceBundle.getBundle("property"); Enumeration infoCN = resource.getKeys(); // Enumeration转换为Iterator 的对象适配器(这里纯粹是练习适配器模式) EnumerationAdapter enumerationAdapter= new EnumerationAdapter(infoCN); while( enumerationAdapter.hasNext() ) { String CN = (String) enumerationAdapter.next(); System.out.println(CN); String handerType = getHanderCN(CN); System.out.println(handerType); Class<?> classObject = Class.forName(handerType); //Class classObject = Thread.currentThread().getContextClassLoader().loadClass(handerType); Constructor<?> constructor = null; try { constructor = classObject.getConstructor(new Class[]{ModeDocumentFactory.class} ); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } try { //使用反射将value实例化,将ModeDocumentFactory传给实例 hander = (baseDomHander)constructor.newInstance(this); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } //将处理对象放进内存里 infoClassNameAndHandlerPool.put(CN, hander ); } } public static String getDIR() { return DIR; } public String getHanderCN(String key){ return resource.getString(key); } public static baseDomHander createDocument(Class c,String dir){ baseDomHander bdHander = getHandlerFromPool( c); if(dir!=""&&dir!=null){ DIR=dir; } bdHander.createDocument(DIR); return bdHander; } public static baseDomHander createDocument(BasePojo basepojo ){ baseDomHander bdHander = getHandlerFromPool( basepojo.getClass()); bdHander.createDocument(DIR); return bdHander; } public static void addInfo(BasePojo basepojo ){ baseDomHander bdHander = getHandlerFromPool( basepojo.getClass()); bdHander.addInfo(basepojo); } public static void main(String[] args) { String filename = "d:/friends.xml"; String bookfilename = "d:/books.xml"; ModeDocumentFactory instance = ModeDocumentFactory.getInstance(); BookInfo finfo = creatbookinfo(); //createtmepinfo(); instance.createDocument(BookInfo.class,bookfilename); instance.addInfo(finfo); //instance.addInfo(finfo); //instance.delInfo(finfo); } public static baseDomHander getHandlerFromPool(Class c){ String key = c.getName(); String[] keys = key.split("\\."); String lastKey = keys[keys.length-1]; baseDomHander bdHander = (baseDomHander)infoClassNameAndHandlerPool.get(lastKey); return bdHander ; } public static void delInfo(BasePojo basepojo) { baseDomHander bdHander = getHandlerFromPool( basepojo.getClass()); bdHander.delInfo(basepojo); } public static void changeInfos(BasePojo basepojo) { baseDomHander bdHander = getHandlerFromPool( basepojo.getClass()); bdHander.changeInfo(basepojo); } public static List getinfo() { return null; } public static FriendsInfo createtmepinfo(){ FriendsInfo friendsinfo=new FriendsInfo("gao","lanyungang"); friendsinfo.setQQ("120316879"); friendsinfo.setImage("/images/text.png"); return friendsinfo; } public static BookInfo creatbookinfo(){ BookInfo bookInfo=new BookInfo(); bookInfo.setName("java"); bookInfo.setTitle("java_title"); bookInfo.setContext("内容"); bookInfo.setPrice("1000"); bookInfo.setShow("yes"); return bookInfo; } }
9.
BookInfo=com.ysen.dom02.bookDomHander FriendsInfo=com.ysen.dom02.friendDomHander