xmap使用实例
例如,我要读入这样的xml格式:
【待读入的xml文件】
<?xml version="1.0" encoding="GBK"?> <operations> <operation op="ADD"> <topicmessage> <string>100, 101</string> <string>200, 201</string> </topicmessage> <context> <string>mysqlcluster, 100</string> <string>mysqlcluster, 200</string> </context> </operation> </operations>
那么,很显然,operations是什么?里面的operation又是什么?别着急,来了。
【xml映射为的java类们】
@XObject("operations") public class Operations { @XNodeList(value="operation", type=ArrayList.class, componentType=Operation.class) private List<Operation> operations; public List<Operation> getOperations() { return operations; } public void setOperations(List<Operation> operations) { this.operations = operations; } }
@XObject public class Operation { @XNode("@op") private String op; @XNodeList(value = "topicmessage/string", type = ArrayList.class, componentType = String.class) private List<String> topicmessages = Collections.emptyList(); ; @XNodeList(value = "context/string", type = ArrayList.class, componentType = String.class) private List<String> contexts = Collections.emptyList(); ; @XNodeList(value = "cluster/string", type = ArrayList.class, componentType = String.class) private List<String> clusters = Collections.emptyList(); ; public String getOp() { return op; } public void setOp(String op) { this.op = op; } public List<String> getTopicmessages() { return topicmessages; } public void setTopicmessages(List<String> topicmessages) { this.topicmessages = topicmessages; } public List<String> getContexts() { return contexts; } public void setContexts(List<String> contexts) { this.contexts = contexts; } public List<String> getClusters() { return clusters; } public void setClusters(List<String> clusters) { this.clusters = clusters; } }
好,已经建好了xml-class间的映射关系。可以开始读了:
【xmap读取xml文件】
public final List<Operation> readXML() { XMap xmap = new XMap(); xmap.register(Operations.class); // 加载文件 Object[] result = null; try { URL url = new File(dir, filename).toURL(); result = (Object[]) xmap.loadAll(url); } catch (Exception e) { String msg = "解析" + filename + "时发生错误"; LOGGER.error(msg, e); throw new PairFileException(msg, e); } if (result.length == 0) { return null; } else { Object element = result[0]; Operations c = (Operations) element; return c.getOperations(); } }
好了,读讲完了。那写呢?我现在想生成这样格式的xml文件,可以吗,怎么做呢。假设你的operation和operations内容,都已经准备好了,那么:
【xmap写xml文件】
XMap xmap = new XMap(); xmap.register(Operations.class); List<String> filters = new ArrayList<String>(); String result = xmap.asXmlString(myOperations, "GBK", filters, true);
xmap语法,可参见附件。