import java.io.File; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXB; import org.apache.log4j.Logger; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; import cn.com.starit.ts.nms.collect.pon.snmp.beans.ConfigInfo; public class ConfigXml { private static Logger logger = Logger.getLogger(ConfigXml.class); String filePath=""; public ConfigXml() { } public ConfigXml(String filePath){ this.filePath=filePath; } /** * JAXB方式读XML文件 * @param file * @param clazz * @return */ public Object getConfigXmlByJAXB(File file,Class<?> clazz){ return JAXB.unmarshal(file,clazz); } /** * JAXB方式写XML文件 * @param clazz * @param file */ public void setConfigXmlByJAXB(Object obj,File file){ JAXB.marshal(obj,file); } /** * load 载入一个xml文档 * @return 成功返回Document对象,失败返回null * @param 文件路径 */ public Document load(String filename) { Document document = null; try { SAXReader saxReader = new SAXReader(); document = saxReader.read(new File(filename)); } catch (Exception ex) { logger.error("解析配置文件失败:" + ex.getMessage()); } return document; } //*地址改成配置的 @SuppressWarnings("unchecked") public List<Element> getProcessList() { String home = System.getenv("TSPON_HOME"); //环境变量 if (home == null) { home = "D:/SNMP"; } filePath= home + "/collect/config/snmp_config.xml"; Document doc = load(filePath); List<Element> process_list = new ArrayList<Element>(); if (doc == null) { return process_list; } Element define = doc.getRootElement().element("process_list"); List<Element> defineNodes = define.elements("process"); return defineNodes; } public ConfigInfo getCollWayConfig(){ String home = System.getenv("TSPON_HOME"); if (home == null) { home = "D:/SNMP"; } String collWayFile = home + "/collect/config/snmp_collecter.xml"; return(ConfigInfo) getConfigXmlByJAXB(new File(collWayFile),ConfigInfo.class);//把一个xml文件与一个javabean对象结合起来 } public static void main(String[] a) { // ConfigXml xml=new ConfigXml("d:\\snmp_collect_config.xml"); // xml.getProcessList(); ConfigXml xml = new ConfigXml(); ConfigInfo config = new ConfigInfo(); //写 List<ConfigInfo> list = new ArrayList<ConfigInfo>(); for(int i=1;i<5;i++){ ConfigInfo configFactory = new ConfigInfo(); configFactory.setFactoryId(i); configFactory.setCollType(1); configFactory.setOltCollMode(1); configFactory.setOnuCollMode(1); configFactory.setSendLength(5); list.add(configFactory); } config.setConfig(list); xml.setConfigXmlByJAXB(config,new File("d:/a.xml")); //读 config = (ConfigInfo)xml.getConfigXmlByJAXB(new File("d:/a.xml"),ConfigInfo.class); for(ConfigInfo con:config.getConfig()){ System.out.println(con.getOltCollMode()); } } }
JAXB方式读写XML文件
时间: 2024-10-08 19:35:14