四、将数据文件模型导出到XML文件
考虑到数据格式定义的可维护性,我们采用DOM模型和XML框架文件来管理和导出数据文件模型。通过建立DOM模型的数据表(Table),记录(Record),关键字段(Primary Key)和字段(Field)等结点来与数据文件模型元素建立对应,再由DOM模型导出到XML文件。实施的步骤是:
1.建立空的DOM模型
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); //Dummy document //Root node Element root = doc.createElement("TableStructure"); doc.appendChild(root); Table Structure是所有数据表定义的根结点,该结点下可以包含多个数据表定义。
2.定义数据表和记录字段
public Element defineTable(Document __doc, Element __root, String __name, String __fieldCount, String __primaryKey) { Element table = __doc.createElement("Table"); __root.appendChild(table); //One table have 3 attributes table.setAttribute("NAME", __name); table.setAttribute("FIELD_COUNT", __fieldCount); table.setAttribute("PRIMARY_KEY", __primaryKey); return (table); } public void defineField(Document __doc, Element __table, String __name, String __type, String __null, String __default, String __separator) { Element field = __doc.createElement("Field"); __table.appendChild(field); //One field have 4 attributes field.setAttribute("NAME", __name); field.setAttribute("MAX_SIZE", __type); field.setAttribute("NULL", __null); field.setAttribute("DEFAULT", __default); field.setAttribute("SEPARATOR", __separator); //Field may be composite field } 数据表以“Table”结点进行定义,主键的定义存在于数据表的定义中。字段以“Field”结点进行定义,字段的内容及顺序隐含了记录的定义。
3.添加数据表和字段定义到DOM模型
//Defines table Element table = defineTable(__doc, __root, "ROAD", "16", "ID"); //Defines fields defineField(__doc, table, "ID", "13", "NOT", "", ""); //#1 defineField(__doc, table, "CLASS", "3", "NOT", "", ""); //#2 defineField(__doc, table, "WIDTH", "3", "NOT", "", ""); //#3 当数据定义改变时,只需调整数据表以及字段的属性即可。这些调整包括:添加新表/字段,删除表/字段,调整字段顺序,拆分字段,字段合并(字段组合)。
4.将DOM模型结构转换成XML文档
TransformerFactory factory = TransformerFactory.newInstance(); Transformer tf = factory.newTransformer(); DOMSource source = new DOMSource(__doc); StreamResult result = new StreamResult(new File(__fileName)); tf.setOutputProperty(OutputKeys.STANDALONE, "yes"); tf.setOutputProperty(OutputKeys.INDENT, "yes"); tf.transform(source, result); 通过XSLT(Extensible Style sheet Language Transformations)引擎来实现将DOM模型转换成XML文件。详细内容请参见XSLT相关参考。
五、小结
(1)数据文件的模型结构与DOM结构比较近似,使用DOM模型可以完全满足数据文件的模型定义。
(2)DOM模型到XML文件的导出比较透明,这样极大方便了数据模型的维护:只需要DOM模型与数据文件的模型一致即可,不用考虑XML文件的维护的细节。
(3)模型定义的导出可以是“一次导出,多次使用”,只有当数据文件模型发生改变时,才需要重新导出新的XML文档,这样极大方便了模型定义的版本管理。