從XML元素結構到JAVA實現 - 中國WEB開發者網絡 (http://www.webasp.net) -- 技術教程 (http://www.webasp.net/article/) --- 從XML元素結構到JAVA實現 (http://www.webasp.net/article/22/21406.htm) |
| -- 作者:未知 -- 發佈日期: 2005-04-30 |
前幾個月,做項目時整理過一些XML操作的程序。這裡根據自己的編程習慣再做一下整理。XML操作最基本的是SAX,DOM了。但這裡不是談SAX,DOM怎麼使用。而是從XML元素的角度談其java的實現。XML是由多個元素組成,可以分成XMLElement、XMLSimpleElement、XMLComplexElement、XMLCollection、XMLCollectionElement等幾種基本類型,從類名你基本就可以判斷出該類所描述的XML對象了。 下面以一個例子來做描述: <?xml version="1.0" encoding="GB2312"?> <Package name = "abc"> <File name = "file"> <Sheet name = "sheet"> <Styles> <style id = "0" name = "a"> <align>2</align> <borders> <border id = "0" type = "left" value = "1" /> <border id = "1" type = "right" value = "3" /> </borders> <font name = "細明體" color = "3" height = "20" /> </style> </Styles> <Columns> <Column id = "0" columnid = "0" width = "10" /> </Columns> <Regions> <Region id = "0" rowid = "1" columnform = "0" columnto = "3" /> </Regions> <Cells> <cell id = "1" row="0" column = "0" style = "a" value ="測試"/> <cell id = "2" row="2" column = "2" value =" 測試2" /> </Cells> </Sheet> </File> </Package> 該配置文件是個XML—>EXCEL的XML文件,描述了EXCEL中的一些對象,比如文件名,字體,行,列等。其中Package是一個XMLComplexElement(混合類型),Cells(單元格集)是個XMLCollection(容器類),cell (單元格)是XMLCollectionElement(容器中的元素)<cell id = "1" row="0" column = "0" style = "a" value ="測試"/> 中的id 就是XMLAttribute(屬性)。所有的XML文件都是由這些基本的元素組成。定義出最基本的XML元素後,那麼在程式中怎麼也把它們之間的關係定義出來呢?以cell元素為例子代碼如下: public class Cell extends XMLCollectionElement { private XMLAttribute attrRow=new XMLAttribute("row"); private XMLAttribute attrStyle=new XMLAttribute("style"); private XMLAttribute attrColumn=new XMLAttribute("column"); private XMLAttribute attrValue=new XMLAttribute("value"); private XMLInterface xmlInterface = null ; public Cell (Cells ass) { super(ass); fillStructure(); } protected void fillStructure() { super.fillStructure(); attrId.setReadOnly(true); isRequired=true; complexStructure.add(attrStyle); complexStructure.add(attrRow); complexStructure.add(attrColumn); complexStructure.add(attrValue); } } 源代碼下載 http://www.51sports.org/xml.rar |
| webasp.net |