当前位置:编程学习 > JSP >>

从XML元素结构到JAVA实现

答案:
前几个月,做项目时整理过一些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


上一个:JDK 1.5学习之RowSet
下一个:EclipsePro: Java Tools for Professional Eclipse Developers

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,