服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

java&xml心得(三)


  作者-- joinme
(续 java&xml心得(二) )

xmlbuilder.class 主要是把指定的document.node对象转换成规范的xml字符串。用的是ibm的xml4j解析器.代码如下:
package com.ceic.workflow.xml;
import java.io.outputstreamwriter;
import java.io.printwriter;
import java.io.unsupportedencodingexception;
import org.w3c.dom.attr;
import org.w3c.dom.document.
import org.w3c.dom.element;
import org.w3c.dom.namednodemap;
import org.w3c.dom.node;
import org.w3c.dom.nodelist;
import com.ibm.xml.parsers.*;

/**
* title: 有效xml 字符串生成工具
* description: 有效xml 字符串生成工具
* copyright: copyright (c) 2003
* company: 国电信息中心
* @author 张治中
* @version 1.0
* 有效xml 字符串生成工具
* 例如:
* xmlbuilder build=new xmlbuilder();
* document.nbspdoc=((document.class.forname("com.ibm.xml.dom.document.mpl").newinstance())
* ..........
* build.printdomtree(doc);
* string xmlstring=build.getxmlresult();
* 再把xmlstring用xmloutput类去输出成xml文件.
*/
public class xmlbuilder
{
private string lineseparator=" ";
private string xmlstring="";
private int indentlevel=0;
protected static string standard_indent=" ";
private string xmlheader="<?xml version="1.0" ?>";
private int currentlevel=0;
/**
* 生成xml字符串.
* @param node 要生成字符串的document.其它node.
*/
public void printdomtree(node node){
printdomtree(node,indentlevel,false);
}

/**
* 生成xml字符串.
* @param node 要生成字符串的document.其它node.
* @param notop 是否去除头尾,如果为document.象去掉<?xml.../?>头
*/
public void printdomtree(node node,boolean notop){
printdomtree(node,indentlevel,notop);
}
/**
* 生成xml字符串.
* @param node 要生成字符串的document.其它node.
* @param level 节点的深度.(中间变量)
* @param notop 是否去除头尾,如果为document.象去掉<?xml.../?>头
*/
private void printdomtree(node node,int level,boolean notop)
{
int templevel=level;
int find=0;
short toptype=0;
string topvalue="";
int type = node.getnodetype();
switch (type)
{
// print the document.nbspelement
case node.document.node:
{
find++;
if(!notop||find>1){
xmlstring+=xmlheader+lineseparator;
}else{
toptype=node.document.node;
}
printdomtree(((document.node).getdocument.lement(),templevel+1,false);
break;
}

// print element with attributes
case node.element_node:
{ find++;

if(!notop||find>1){
currentlevel=templevel;
xmlstring+=printindent(templevel);
xmlstring+=lineseparator+"<";
xmlstring+=node.getnodename();
namednodemap attrs = node.getattributes();
for (int i = 0; i < attrs.getlength(); i++)
{
node attr = attrs.item(i);
xmlstring+=" " + attr.getnodename() +"="" + attr.getnodevalue() +""";
}
xmlstring+=">"+lineseparator;
}
else{
toptype=node.element_node
topvalue="</"+node.getnodename()+">"+lineseparator;
}
nodelist children = node.getchildnodes();
if (children != null)
{
int len = children.getlength();
for (int i = 0; i < len; i++)
printdomtree(children.item(i),templevel+1,false);
}

break;
}

// handle entity reference nodes
case node.entity_reference_node:
{
find++;
xmlstring+="&";
xmlstring+=node.getnodename();
xmlstring+=";";
break;
}

// print cdata sections
case node.cdata_section_node:
{
find++;
xmlstring+="<![cdata[";
xmlstring+=node.getnodevalue();
xmlstring+="]]>";
break;
}

// print text
case node.text_node:
{
find++;
// string temp=node.getnodevalue();
// if(!temp.equals(" ")&&!temp.equals(" ")&&!temp.equals(" "))
xmlstring+=node.getnodevalue();
break;
}

// print processing instruction
case node.processing_instruction_node:
{
find++;
xmlstring+="<?";
xmlstring+=node.getnodename();
string data = node.getnodevalue();
{
xmlstring+=" ";
xmlstring+=data;
}
xmlstring+="?>";
break;
}
}

if (type == node.element_node)
{
find++;
if(currentlevel!=templevel){
xmlstring+=printindent(templevel);
xmlstring+=lineseparator;
}
xmlstring+="</";
xmlstring+=node.getnodename();
xmlstring+=">"+lineseparator;
}
if(notop&&toptype==node.element_node){
int len=xmlstring.length()
int tlen=topvalue.length()
xmlstring=xmlstring.substring(0,len-tlen);
}
}
/**
* 生成行前的standard_indent(一般指空格)
* @param num standard_indent的个数
* @return string
*/
private string printindent(int num){
string temp="";
if(num>0){
for(int i=0;i<num;i++){
temp+=standard_indent;
}
}
return temp;
}
/**
* 设定行前的standard_indent(一般指空格)
* @param indent standard_indent的值
*/
public void setindent(string indent){
standard_indent=indent;
}
/**
* 获得已经生成的xml字符串.在printdomtree(node node)方法后有效
* @return string
*/
public string getxmlresult(){
return xmlstring;
}
/**
* 设定最开始的深度级别(直接影响行前的standard_indent(空格)数)
* @param level 级别数
*/
public void setbeginlevel(int level){
indentlevel=level;
}
/**
* 设定xml文件的xml头
* @param header xml文件xml头。例如:<?xml version="1.0" ?>
*/
public void setxmlheader(string header){
xmlheader=header;
}
/**
* 设定换行符 默认为" "
* @param lineseparator 换行分割符,默认为" "
*/
public void setlineseparator(string lineseparator){
lineseparator=lineseparator;
}
}
xmloutput.class 功能是用指定的string或inputstream生成文件(不一定是xml文件)。代码如下:
package com.ceic.workflow.xml
import org.w3c.dom.*;
import java.io.*;
import java.util.*;
/**
* title: 有效xml 字符串生成xml文件的工具
* description: 有效xml 字符串生成xml文件的工具
* copyright: copyright (c) 2003
* company: 国电信息中心
* @author 张治中
* @version 1.0
*/
public class xmloutput{
private string objectpath;
private string encoding="utf8";
public xmloutput(){

}
/**
* 构造器
* @param filepath 生成的目标xml文件位置.
*/
public xmloutput(string filepath){
objectpath=filepath;
}
/**
* 设定生成的目标xml文件的位置
* @param filepath 生成的目标xml文件位置.
*/
public void setobjectpath(string filepath){
objectpath=filepath;
}
/**
* 设定生成xml文件的编码格式
* @param encod 生成xml文件的编码格式,默认为 utf8
*/
public void setencoding(string encod){
encoding=encod;
}
/**
* 根据指定的xmlstring生成xml文件.
* @param xmlstring 指定的xml字符串
*/
public void output(string xmlstring){
if(!checkobject()) {
system.out.println("没有指定要写入的文件");
return;
}
try{
// stringbufferinputstream in=new stringbufferinputstream(xmlstring);
fileoutputstream out=new fileoutputstream(new file(objectpath));
java.io.writer write=new java.io.outputstreamwriter(out,encoding);
write.write(xmlstring);
write.close()
}catch(exception ee){
system.out.println(ee.getmessage());
system.out.println("写文件出错");
}
}
/**
* 根据指定的输入流生成xml文件.
* @param in 指定的inputstream
*/
public void output(inputstream in){
if(!checkobject()) {
system.out.println("没有指定要写入的文件");
return;
}
try{
stringbuffer temp=new stringbuffer();
byte[] tempbyte=new byte[1024];
while(in.read(tempbyte)!=-1){
temp.append(new string(temp));
}
in.close()
string result=temp.tostring()
fileoutputstream out=new fileoutputstream(new file(objectpath));
java.io.writer write=new java.io.outputstreamwriter(out,encoding);
write.write(result);
write.close()
}catch(exception eee){
system.out.println(eee.getmessage());
system.out.println("写文件出错");
}


}
/**
* 检查文件path是否为空
* @return boolean
*/
private boolean checkobject(){
if(objectpath!=null&&objectpath.length() >0) return true;
return false;
}
}
有了这些xml的操作工具后,下一步就是接着来进行实际的应用。在我以前的项目中(二次开发的),有个遗留问题就是tree型权限和tree型角色的交互(包括各自的维护)。当时在表现层是用的 jsp+applet实现哪个tree图(给applet传入一个xml格式的文件流)。文件格式如下:
<node icon="http://www.itus.cn/zdtadmin/images/cluster_folder.gif" label="退出登陆" target="_top" url="/zdtadmin/login.jsp">
</node>
<node icon="http://www.itus.cn/zdtadmin/images/cluster_folder.gif" label="角色维护" target="mainframe" url="/zdtadmin/default.jsp">
<node icon="http://www.itus.cn/zdtadmin/images/cluster_folder.gif" label="添加角色" target="mainframe" url="/zdtadmin/peradmin/role_edit.jsp">
</node>
<node icon="http://www.itus.cn/zdtadmin/images/cluster_folder.gif" label="角色<->栏目" target="mainframe" url="/zdtadmin/peradmin/role_tree.jsp">
</node>
<node icon="http://www.itus.cn/zdtadmin/images/cluster_folder.gif" label="角色<->用户" target="mainframe" url="/zdtadmin/peradmin/role_user.jsp">
</node>
</node>
其实就是一个比较规范的xml文档,在tree结构只有两层时比较容易就可以用jsp来out.println()出来。但是当结构边复杂时用jsp就不够了。在加上有权限在里面,问题就更复杂化了。在了解到了xml后及做了上面的一些工作后.决定用xml(通过递归方法生成tree型结构的xml)来实现。代码如下:
package com.ceic.tree;
import java.io.*;
import org.w3c.dom.*;
import java.util.*;
import com.ceic.workflow.xml.*;
import com.ceic.publicsource.*;
import com.ceic.resultsets.*;

public class createtree {
private boolean start=false;
private result rs;
private xmltool tool;
private document.nbspdoc;
private int beginlevel=0;
private string indent=" ";
private string end=" ";
private string header="<?xml version="1.0" ?>";
private string parenttreeid="tree_id_p";
private string treeid="tree_id";
private string defaultparent="0";
private string nodename="node";
private int maxattrs=20;
private int maxsize=20;
public int[] vec;
private int mark=0;
private string checkone="label";
private string[] nodeattrlist;
private string colflag="#";
private string[] nodeattrvaluelist;
private string defaultflag="@";
private hashtable mapping=new hashtable();
private vector collist=new vector();
private string rootname="zzz_test";
private boolean enablemakeup=false;
public createtree(){
try{
rs=resultfactory.getresult("vector");
rs.setconntype("jdbc");
string sql="select * from cm_tree";
rs.setsql(sql);
rs.create()
}catch(exception exec){
system.out.println("初始化无效,请通过setresult()设定数据源");
}
tool=xmltoolfactory.getxmltool()
doc=tool.createdocument.)
tool.setdocument.ource(doc);
init();
}
public void setparenttreeid(string parenttreeid){
if(parenttreeid!=null&&parenttreeid.length() >0) parenttreeid=parenttreeid;
}
public void settreeid(string treeid){
if(treeid!=null&&treeid.length() >0) treeid=treeid;
}
public void setdefaultparent(string defaultp){
if(defaultp!=null&&defaultp.length() >0)
defaultparent=defaultp;
}
public void setmaxtreelevel(int maxsize){
if(maxsize>0){
maxsize=maxsize;
vec=null;
vec=new int[maxsize];
vec[0]=0;
}
}
public void setcheckone(string checkone){
if(checkone!=null&&checkone.length() >0){
checkone=checkone;
}
}
public void setheader(string header){
try{
if(header!=null&&header.length() >0){
header=header;
tool.setheader(header);
}
}catch(exception e){
system.out.println("xmltool不存在");
}
}
public void setdocument.document.nbspdocs){
if(docs!=null){
doc=docs;
tool.setdocument.ource(doc);
}
}
public void setxmltool(xmltool tools){
if(tools!=null){
tool=tools;
doc=tool.createdocument.)
tool.setdocument.ource(doc);

}
}
public void setresult(result tools){
if(tools!=null){
close()
rs=tools;
}
}
public void setmaxattrs(int max){
if(max>0) maxattrs=max;
}
public void setattrlist(string[] list){
if(list.length >0){
if(list.length >maxattrs) maxattrs=list.length
nodeattrlist=null;
nodeattrlist=new string[maxattrs];
nodeattrvaluelist=null;
nodeattrvaluelist=new string[maxattrs];
collist.clear()
for(int i=0;i<list.length i++){
nodeattrlist[i]=list[i];
collist.addelement(nodeattrlist[i]);
}
}
}
public void setvaluelist(string[] list){
if(list.length >0){
if(list.length >maxattrs) maxattrs=list.length
nodeattrvaluelist=null;
nodeattrvaluelist=new string[maxattrs];
mapping.clear()
for(int i=0;i<collist.size();i++){
nodeattrvaluelist[i]=list[i];
mapping.put(collist.elementat(i).tostring() ,nodeattrvaluelist[i]);

}
}
}
public void addmapping(string name,string value){
if(name!=null&&name.length() >0){
collist.addelement(name);
mapping.put(name,value);
}
}
public void setcolflage(string colflag){
if(colflag!=null&&colflag.length() >0){
colflag =colflag;
}
}
public void setlineend(string lineend){
if(lineend!=null&&lineend.length() >0){
end=lineend;
}
}
public void settreenodename(string nodename){
if(nodename!=null&&nodename.length() >0&&!nodename.equals(rootname)){
nodename=nodename;
}
}
public document.nbspgetdocument.){
return doc;
}
public xmltool getxmltool(){
return tool;
}
public result getresult(){
return rs;
}
public void setdefaultflag(string flag){
if(flag!=null&&flag.length() >0){
defaultflag=flag;
}
}
public createtree(result rss,xmltool xmltool){
try{
rs=rss;
tool=xmltool;
doc=tool.createdocument.)
tool.setdocument.ource(doc);
init();
}catch(exception eer){
eer.printstacktrace()
system.out.println("初始化失败");
}
}
private void init(){
try{

vec=new int[maxsize];
vec[0]=0;
nodeattrlist=new string[maxattrs];
nodeattrvaluelist=new string[maxattrs];
nodeattrlist[0]="label";
nodeattrlist[1]="icon";
nodeattrlist[2]="url";
nodeattrlist[3]="target";
nodeattrlist[4]="parentid";
nodeattrlist[5]="id";

nodeattrvaluelist[0]=colflag+"tree_name";
nodeattrvaluelist[1]="http://www.itus.cn/zdtadmin/images/cluster_folder.gif";
nodeattrvaluelist[2]=colflag+"tree_address";
nodeattrvaluelist[3]=colflag+"tree_target"+defaultflag+"_blank";
nodeattrvaluelist[4]=colflag+"tree_id_p";
nodeattrvaluelist[5]=colflag+"tree_id";
for(int i=0;i<6;i++){
collist.addelement(nodeattrlist[i]);
mapping.put(nodeattrlist[i],nodeattrvaluelist[i]);
}
}catch(exception eer){
eer.printstacktrace()
system.out.println("初始化失败");
}
}
public void createxml(){
element root=tool.createelement(rootname);
doc.appendchild(root);
tool.setmarksign(nodename);
rs.first()
mark=0;
start=false;
createmaptree(defaultparent,beginlevel,root);
//tool.isenablemakeup();

}
public void createxml(string selfroot,int indexs){
element root;
if(selfroot==null||selfroot.length()==0){
root=tool.createelement(rootname);
doc.appendchild(root);
}
else{
nodelist list=doc.getelementsbytagname(selfroot);
if(list.getlength() >0){
if(indexs>list.getlength()) indexs=0;
else
{
if(indexs>=1) indexs=indexs-1;
else indexs=0;
}
root=((element)doc.getelementsbytagname(selfroot).item(indexs));
//rootname=selfroot;
}else{
root=tool.createelement(rootname);
doc.appendchild(root);
}
}
tool.setmarksign(nodename);
rs.first()
mark=0;
start=false;
createmaptree(defaultparent,beginlevel,root);
//tool.isenablemakeup();

}
public void isenablemakeup(){
enablemakeup=true;
tool.isenablemakeup()
}
public void isnotenablemakeup(){
enablemakeup=false;
tool.isnotenablemakeup()
}
public void createxmlfile(string filepath){
tool.output(filepath,doc);
}
public void createxmlfile(string filepath,boolean notop){
tool.output(filepath,doc,notop);
}
public void createselfxmlfile(string filepath,boolean notop){
tool.output(filepath,doc.getelementsbytagname(rootname).item(0),notop);
}
public void createxmlfile(string filepath,string nodename,int indexs,boolean notop){
nodelist list=doc.getelementsbytagname(nodename);
if(list.getlength() >0){
if(indexs>list.getlength()) indexs=0;
else{
if(indexs>=1) indexs=indexs-1;
else indexs=0;
}
tool.output(filepath,doc.getelementsbytagname(nodename).item(indexs),notop);
}

}
public void setencoding(string encod){
tool.setencoding(encod);
}
private void createmaptree(string type,int level,node node){
try{
int templevel=level;
do{

if(rs.getstring(parenttreeid).equals(type)){
if(!enablemakeup){
text tx=doc.createtextnode(end);
node.appendchild(tx);
createindet(templevel,node);
}
string newtype=rs.getstring(treeid);
element ele=tool.createelement(nodename);
createtreemodel(ele,rs);

// if(checknode(ele,checkone)){

node.appendchild(ele);
templevel++;
mark++;
vec[mark]=0;
rs.first()
createmaptree(newtype,templevel,ele);
// }
}
vec[mark]++;
}while(rs.next());
mark--;
move();
}catch(exception e){
e.printstacktrace()

system.out.println("生成节点失败");
}
}
private void createtreemodel(node node,result rstemp){
try{
// ((element)node).setattribute(label,rstemp.getstring("tree_name"));
// ((element)node).setattribute(icon,icon);
// ((element)node).setattribute(url,rstemp.getstring("tree_address"));
// if(rstemp.getstring("tree_target")!=null&&rstemp.getstring("tree_target").length() >0){
// ((element)node).setattribute(target,rstemp.getstring("tree_target"));
// }
string tempattr,tempvalue,tempcol,tempdefault,tempcolvalue;
for(int i=0;i<collist.size();i++){
tempcol="";
tempdefault="";
tempcolvalue="";
tempattr=collist.elementat(i).tostring()
tempvalue=mapping.get(tempattr).tostring()
if(tempattr!=null&&tempattr.length() >=0){
if(tempvalue.indexof(colflag)>=0){
string[] aaa=thestrings.split(tempvalue,colflag);
string header="";
string thevalue="";
if(aaa.length >1){
header=aaa[0];
thevalue=aaa[1];
}else{
thevalue=aaa[0];
}

string[] temps=thestrings.split(thevalue,defaultflag);
if(temps.length >1) tempdefault=temps[1];
tempcol=temps[0];
tempcolvalue=rstemp.getstring(tempcol);

if(tempdefault.length() >0){
if(tempcolvalue.length() >0){
((element)node).setattribute(tempattr,header+tempcolvalue);
}else{
((element)node).setattribute(tempattr,tempdefault);
}
}else{
((element)node).setattribute(tempattr,header+tempcolvalue);
}
}else{
((element)node).setattribute(tempattr,tempvalue);
}
}
}
}catch(exception ee){
ee.printstacktrace()
system.out.println("建立数据失败");
}
}
public void deletenode(string nodename){
tool.delnode(nodename,nodename,true);
}
private void createindet(int level,node node){

for(int i=0;i<level;i++){
text tx=doc.createtextnode(indent);
node.appendchild(tx);
}

}
private void move(){
if(mark>=0){

rs.first()

for(int i=0;i<vec[mark];i++){

rs.next()
}

}

}
public void close(){
rs.close()

}
private boolean checknode(node node,string onetype){
string label=((element)node).getattribute(onetype);
if(tool.setmark(onetype,label)){
return false;
}
return true;

}
public string getxmlstring(boolean notop){
xmlbuilder builder=new xmlbuilder();
builder.printdomtree(doc,notop);
return builder.getxmlresult()
}
public string getselfxmlstring(boolean notop){
xmlbuilder builder=new xmlbuilder();
node node=doc.getelementsbytagname(rootname).item(0);
builder.printdomtree(node,notop);
return builder.getxmlresult()
}
public vector getparents(string id){
vector vec=new vector();
getparent(id,vec);
return vec;
}

private void getparent(string id,vector vec){
tool.setmarksign(nodename);
tool.setmark(checkone,id);
node node=doc.getelementsbytagname(nodename).item(tool.getindex());
if(node.getparentnode() !=null){
string tempid=((element)node.getparentnode()).getattribute(checkone);
if(tempid!=null&&tempid.length() >0){
if(tempid.equals(defaultparent)){
vec.addelement(defaultparent);
return;
}else{
vec.addelement(tempid);
getparent(tempid,vec);
}
}
}
}
public vector getsons(string id){
vector vec=new vector();
getson(id,vec);
return vec;
}
private void getson(string id,vector vec){
tool.setmarksign(nodename);
tool.setmark(checkone ,id);
node node=doc.getelementsbytagname(nodename).item(tool.getindex());
nodelist list= node.getchildnodes()
if(list.getlength() >0){
string tempid;
for(int i=0;i<list.getlength() i++){
if(list.item(i).getnodetype()==node.element_node){
tempid=((element)list.item(i)).getattribute(checkone);
if(tempid!=null&&tempid.length() >0){
vec.addelement(tempid);
getson(tempid,vec);
}
}
}
}
}

//
//public static void main(string[] a){
// string[] name={"icon","label","url","target","id","parentid"};
//string[] value={"/zdtadmin/images/cluster_folder.gif","#tree_name","#tree_address","#tree_target@mainframe","#tree_id","#tree_id_p"};
//createtree create=new createtree();
//xmltool tool=xmltoolfactory.getxmltool()
//result rs=resultfactory.getresult("vector");
//rs.setconntype("jdbc");
//rs.setsql("select * from cm_tree where tree_id in(3,44,1,32,29) and tree_enable=′1′ order by tree_id");
//rs.create()
//create.setresult(rs);
//create.setxmltool(tool);
//create.isenablemakeup()
//create.setattrlist(name);
//create.setvaluelist(value);
//create.setcheckone("id");
//create.setdefaultparent("0");
//create.settreeid("tree_id");
//create.setparenttreeid("tree_id_p");
//create.settreenodename("node");
//create.setencoding("gbk");
//create.createxml();
//vector vec=create.getparents("30");
//for(int i=0;i<vec.size() i++){
// system.out.println(vec.elementat(i));
//}
//create.deletenode("id");
//create.deletenode("parentid");
//create.createselfxmlfile("d:/tomcat/webapps/test_self.xml",true);
//create.close()
//
//
//
//}




}
main()是 实例。private result rs;是自定义记录集容器( vector装所有记录,vector中对象hashtable,hashtable中为字段名和字段值,还有一个字段名列表vector,可能有什么安全隐患,因为我自己对vector,hashtable不是很了解,希望高手指点).通过这种xml的解决方法,就很好解决了tree图显示,并解决了tree结构中的结构编辑(主要好处是保证tree结构的完整性,例如父节点休眠,所有子节点也休眠,激活子节点必须保证父节点已经被激活。),如果没有xml文档结构,这些操作将是很复杂的递归算法,并且会频繁的操作数据库。
最后一个例子:数据库数据和xml文件同步。
代码如下:
package com.ceic.tree;
import com.ceic.connpool.*;
import com.ceic.resultsets.*;
import com.ceic.publicsource.*;
import java.util.*;
import com.ceic.workflow.xml.*;
import org.w3c.dom.*;

/**
* <p>title: </p>
* <p>description: </p>
* <p>copyright: copyright (c) 2003</p>
* <p>company: </p>
* @author unascribed
* @version 1.0
*/

public class tabletoxml {
private boolean start=false;
private result rs;
private xmltool tool;
private document.nbspdoc;
private int beginlevel=0;
private string indent=" ";
private string end=" ";
private string header="<?xml version="1.0" ?>";
private int maxattrs=20;
private int mark=0;
private string checkone="label";
private string[] nodeattrlist;
private string colflag="#";
private string[] nodeattrvaluelist;
private string defaultflag="@";
private hashtable mapping=new hashtable();
private vector collist=new vector();
private string rootname="table";
private string nodename="col";
private boolean enablemakeup=false;
private int tempindex=0;
private void init(){
try{
nodeattrlist=new string[maxattrs];
nodeattrvaluelist=new string[maxattrs];
nodeattrlist[0]="label";
nodeattrlist[1]="icon";
nodeattrlist[2]="url";
nodeattrlist[3]="target";
nodeattrlist[4]="parentid";
nodeattrlist[5]="id";

nodeattrvaluelist[0]=colflag+"tree_name";
nodeattrvaluelist[1]="http://www.itus.cn/zdtadmin/images/cluster_folder.gif";
nodeattrvaluelist[2]=colflag+"tree_address";
nodeattrvaluelist[3]=colflag+"tree_target"+defaultflag+"_blank";
nodeattrvaluelist[4]=colflag+"tree_id_p";
nodeattrvaluelist[5]=colflag+"tree_id";
for(int i=0;i<6;i++){
collist.addelement(nodeattrlist[i]);
mapping.put(nodeattrlist[i],nodeattrvaluelist[i]);
}
}catch(exception eer){
eer.printstacktrace()
system.out.println("初始化失败");
}
}
public tabletoxml() {
tool=xmltoolfactory.getxmltool()
doc=tool.createdocument.)
tool.setdocument.ource(doc);
init();
}
public tabletoxml(result rs) {
setresult(rs);
tool=xmltoolfactory.getxmltool()
doc=tool.createdocument.)
tool.setdocument.ource(doc);
init();
}
public tabletoxml(result rs,xmltool toolss) {
setresult(rs);
setxmltool(toolss);
init();
}
public void setcheckone(string checkone){
if(checkone!=null&&checkone.length() >0){
checkone=checkone;
}
}
public void setheader(string header){
try{
if(header!=null&&header.length() >0){
header=header;
tool.setheader(header);
}
}catch(exception e){
system.out.println("xmltool不存在");
}
}
public void setdocument.document.nbspdocs){
if(docs!=null){
doc=docs;
tool.setdocument.ource(doc);
}
}
public void setxmltool(xmltool tools){
if(tools!=null){
tool=tools;
doc=tool.createdocument.)
tool.setdocument.ource(doc);

}
}
public void setresult(result tools){
if(tools!=null){
close()
rs=tools;
}
}
public void setmaxattrs(int max){
if(max>0) maxattrs=max;
}
public void setattrlist(string[] list){
if(list.length >0){
if(list.length >maxattrs) maxattrs=list.length
nodeattrlist=null;
nodeattrlist=new string[maxattrs];
nodeattrvaluelist=null;
nodeattrvaluelist=new string[maxattrs];
collist.clear()
for(int i=0;i<list.length i++){
nodeattrlist[i]=list[i];
collist.addelement(nodeattrlist[i]);
}
}
}
public void setvaluelist(string[] list){
if(list.length >0){
if(list.length >maxattrs) maxattrs=list.length
nodeattrvaluelist=null;
nodeattrvaluelist=new string[maxattrs];
mapping.clear()
for(int i=0;i<collist.size();i++){
nodeattrvaluelist[i]=list[i];
mapping.put(collist.elementat(i).tostring() ,nodeattrvaluelist[i]);

}
}
}
public void addmapping(string name,string value){
if(name!=null&&name.length() >0){
collist.addelement(name);
mapping.put(name,value);
}
}
public void setcolflage(string colflag){
if(colflag!=null&&colflag.length() >0){
colflag =colflag;
}
}
public void setlineend(string lineend){
if(lineend!=null&&lineend.length() >0){
end=lineend;
}
}
public void settreenodename(string nodename){
if(nodename!=null&&nodename.length() >0&&!nodename.equals(rootname)){
nodename=nodename;
}
}
public document.nbspgetdocument.){
return doc;
}
public xmltool getxmltool(){
return tool;
}
public result getresult(){
return rs;
}
public void setdefaultflag(string flag){
if(flag!=null&&flag.length() >0){
defaultflag=flag;
}
}
public void isenablemakeup(){
enablemakeup=true;
tool.isenablemakeup()
}
public void isnotenablemakeup(){
enablemakeup=false;
tool.isnotenablemakeup()
}

public void createxmlfile(string filepath){
tool.output(filepath,doc);
}
public void createxmlfile(string filepath,boolean notop){
tool.output(filepath,doc,notop);
}
public void createselfxmlfile(string filepath,boolean notop){
tool.output(filepath,doc.getelementsbytagname(rootname).item(0),notop);
}
public void createxmlfile(string filepath,string nodename,int indexs,boolean notop){
nodelist list=doc.getelementsbytagname(nodename);
if(list.getlength() >0){
if(indexs>list.getlength()) indexs=0;
else{
if(indexs>=1) indexs=indexs-1;
else indexs=0;
}
tool.output(filepath,doc.getelementsbytagname(nodename).item(indexs),notop);
}

}
public void setencoding(string encod){
tool.setencoding(encod);
}
public void setrootattr(string name,string value){
try{
if(name!=null&&name.length() >0) ((element)doc.getelementsbytagname(rootname).item(tempindex)).setattribute(name,value);
}catch(exception e){
system.out.println("还没有建立document.象或root element对象"+e.getmessage());
}
}
public void createxml(boolean collistauto,boolean checkone){
element root=tool.createelement(rootname);
doc.appendchild(root);
tool.setmarksign(nodename);
rs.first()
if(collistauto){
vector vec=(vector)rs.getmetadata()
if(vec.size() >this.maxattrs ) {
maxattrs=vec.size()
nodeattrlist=null;
nodeattrvaluelist=null;
nodeattrlist=new string[maxattrs];
nodeattrvaluelist=new string[maxattrs];
}
if(collist!=null) {collist.removeallelements() collist .clear() }
if(mapping!=null) {mapping .clear() }
for(int k=0;k<vec.size() k++){
nodeattrlist[k]=vec.elementat(k).tostring()
nodeattrvaluelist[k]=colflag+nodeattrlist[k];
collist.addelement(nodeattrlist[k]);
mapping.put(nodeattrlist[k],nodeattrvaluelist[k]);
}
}
mark=0;
start=false;
createmaptree(beginlevel,root,checkone);
//tool.isenablemakeup();

}
public void createxml(string selfroot,int indexs,boolean collistauto,boolean checkone){
element root;
if(selfroot==null||selfroot.length()==0){
root=tool.createelement(rootname);
doc.appendchild(root);
}
else{
nodelist list=doc.getelementsbytagname(selfroot);
if(list.getlength() >0){
if(indexs>list.getlength()) indexs=0;
else
{
if(indexs>=1) indexs=indexs-1;
else indexs=0;
}
root=((element)doc.getelementsbytagname(selfroot).item(indexs));
rootname=selfroot;
tempindex=indexs;
}else{
root=tool.createelement(rootname);
doc.appendchild(root);
}
}
tool.setmarksign(nodename);
rs.first()
if(collistauto){
vector vec=(vector)rs.getmetadata()
if(vec.size() >this.maxattrs ) {
maxattrs=vec.size()
nodeattrlist=null;
nodeattrvaluelist=null;
nodeattrlist=new string[maxattrs];
nodeattrvaluelist=new string[maxattrs];
}
if(collist!=null) {collist.removeallelements() collist .clear() }
if(mapping!=null) {mapping .clear() }
for(int k=0;k<vec.size() k++){
nodeattrlist[k]=vec.elementat(k).tostring()
nodeattrvaluelist[k]=colflag+nodeattrlist[k];
collist.addelement(nodeattrlist[k]);
mapping.put(nodeattrlist[k],nodeattrvaluelist[k]);
}
}
mark=0;
start=false;
createmaptree(beginlevel,root,checkone);
//tool.isenablemakeup();

}
private void createmaptree(int level,node node,boolean checkone){
try{
int templevel=level;
do{
element ele=tool.createelement(nodename )
createtreemodel(ele,rs);
if(checknode(ele,checkone)){
if(!enablemakeup){
text tx=doc.createtextnode(end);
node.appendchild(tx);
createindet(templevel,node);
}
node.appendchild(ele);
}
}while(rs.next() );
}catch(exception e){
e.printstacktrace()

system.out.println("生成节点失败");
}
}

private void createtreemodel(node node,result rstemp){
try{
// ((element)node).setattribute(label,rstemp.getstring("tree_name"));
// ((element)node).setattribute(icon,icon);
// ((element)node).setattribute(url,rstemp.getstring("tree_address"));
// if(rstemp.getstring("tree_target")!=null&&rstemp.getstring("tree_target").length() >0){
// ((element)node).setattribute(target,rstemp.getstring("tree_target"));
// }
string tempattr,tempvalue,tempcol,tempdefault,tempcolvalue;
for(int i=0;i<collist.size();i++){
tempcol="";
tempdefault="";
tempcolvalue="";
tempattr=collist.elementat(i).tostring()
tempvalue=mapping.get(tempattr).tostring()
if(tempattr!=null&&tempattr.length() >=0){
if(tempvalue.indexof(colflag)>=0){
string[] aaa=thestrings.split(tempvalue,colflag);
string header="";
string thevalue="";
if(aaa.length >1){
header=aaa[0];
thevalue=aaa[1];
}else{
thevalue=aaa[0];
}

string[] temps=thestrings.split(thevalue,defaultflag);
if(temps.length >1) tempdefault=temps[1];
tempcol=temps[0];
tempcolvalue=rstemp.getstring(tempcol);

if(tempdefault.length() >0){
if(tempcolvalue.length() >0){
((element)node).setattribute(tempattr,header+tempcolvalue);
}else{
((element)node).setattribute(tempattr,tempdefault);
}
}else{
((element)node).setattribute(tempattr,header+tempcolvalue);
}
}else{
((element)node).setattribute(tempattr,tempvalue);
}
}
}
}catch(exception ee){
ee.printstacktrace()
system.out.println("建立数据失败,可能的原因是指定的节点值的列表中的元素中用到了不能获取的字段。");
}
}
public void deletenode(string nodename){
tool.delnode(nodename,nodename,true);
}
private void createindet(int level,node node){

for(int i=0;i<level;i++){
text tx=doc.createtextnode(indent);
node.appendchild(tx);
}

}
public void close(){
if(rs!=null) rs.close()

}
private boolean checknode(node node,string onetype){
string label=((element)node).getattribute(onetype);
if(tool.setmark(onetype,label)){
return false;
}
return true;

}
public string getxmlstring(boolean notop){
xmlbuilder builder=new xmlbuilder();
builder.printdomtree(doc,notop);
return builder.getxmlresult()
}

public static void main(string args[]){
string[] name={"label","url","target","id","parentid"};
string[] value={"#tree_name","#tree_address@/zdtadmin/default.jsp","#tree_target@_blank","#tree_id","#tree_id_p"};//#开头表示读取指定的字段名的值,@后面跟的是#字段名读取没有值或为null时的默认值 ,可以做简单的组合。比如: "login.jsp?id=#tree_name@1001"
result rs=resultfactory.getresult("vector");
rs.setconntype("jdbc");
rs.setsql("select * from cm_tree where tree_enable=′1′");
rs.create()
tabletoxml ttx=new tabletoxml(rs);
ttx.setattrlist(name);
ttx.setvaluelist(value);
// ttx.setencoding("gbk");
ttx.setheader("<?xml version="1.0" ?>");
ttx.createxml(false,false);//第一个参数是是否用sql中全部的字段,否则用指定的字段和值的列表。第2个参数指
//是否检查唯一性。通过ttx.setcheckone(string str) 设定唯一字段.
ttx.setrootattr("name","cm_tree");
ttx.createxmlfile("d:/xmltest/example/ttx2.xml");
ttx.close()
system.out.println(ttx.getxmlstring(true));
}


}
其中的result同上。不过生成的xml中把字段名都当作attribute来处理(不想太复杂)。
以上是我在接触xml后对xml的理解和实践。用的是最笨的方法(手工操作xml),写出来就是希望能从高手的意见中学到东西。如果有机会,我下一次会把xml和xslt结合的实践例子拿出来和大家一起研究。^_^

扫描关注微信公众号