首页 > 开发 > Java > 正文

从XML元素结构到JAVA实现

2024-07-13 09:54:52
字体:
来源:转载
供稿:网友


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


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表