Learn Java & XML experience (3)

xiaoxiao2021-03-06  23

Xmlbuilder.class mainly puts the specified document. The Node object is converted into a standard XML string. It is an IBM's XML4J parser. The code is as follows:

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.nodeelist;

Import com.ibm.xml.parsers. *;

/ **

* Title: Valid XML String Generation Tool

* Description: Valid XML String Generation Tool

* Copyright: CopyRight (C) 2003

* Company: Guodian Information Center

* @Author Zhang Zhizhong

* @version 1.0

* Valid XML string generation tool

* E.g:

* XMLBuilder Build = new xmlbuilder ();

Document. Nbspdoc = ((Document.class.Forname ("com.ibm.xml.

* Dom.Document. MPL "). NewInstance ())

* ........

* Build.PrintDomtree (DOC);

* String Xmlstring = build.getxmlResult ();

* Add XMLString to the XML file with the XMLOUTPUT class.

* /

Public Class XMLBuilder

{

Private string linesearator = "/ r";

Private string xmlstring = ""

Private int indevel = 0;

protected static string standard_indent = "";

Private string Xmlheader = "";

Private int currentlevel = 0;

/ **

* Generate an XML string.

* @Param Node To generate the operation of the string. Other Node.

* /

Public void printdomtree (node ​​node) {

PrintDomtree (Node, Indenter, False);

}

/ **

* Generate an XML string.

* @Param Node To generate the operation of the string. Other Node.

* @Param NOTOP Whether to remove the head, if you are document. Like the Head

* /

Public Void PrintDomtree (Node Node, Boolean NOTOP) {

Printdomtree (Node, Indenter, NOTOP);

}

/ **

* Generate an XML string.

* @Param Node To generate the operation of the string. Other Node.

* @Param Level node depth. (Intermediate variable)

* @Param NOTOP Whether to remove the head, if you are document. Like the Head * /

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 = PrintInd (Templevel);

Xmlstring = LineseParetor "<";

Xmlstring = node.getnodename ();

NamedNodeMap attrs = node.getattributes ();

For (int i = 0; i

{

Node attr = attrs.Item (i);

Xmlstring = "" attr.getnodename () "= /" "

Attr.getnodeValue () "/" ";

}

Xmlstring = ">" LINESEPARATOR;

}

Else {

TOPTYPE = node.Element_Node

TopValue = "" LINESEPARATOR;

}

Nodelist children = node.getchildnodes ();

if (Children! = NULL)

{

INT LEN = Children.getlength ();

For (int i = 0; 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 = "

Xmlstring = node.getnodeValue ();

Xmlstring = "]]>";

Break;

}

// Print Text

Case Node.Text_Node:

{

Find ;

// String Temp = node.getnodevalue ();

// if (! Temp.equals ("") &&! temp.equals ("/ n")

// &&! Temp.equals ("/ r"))))

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 = PrintInd (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);

}

}

/ **

* Generate Standard_indent before row (general refers to airgage)

* @Param Num Standard_indent

* @Return String

* /

Private string printundent (int Num) {

String temp = "";

IF (Num> 0) {

For (int i = 0; i

TEMP = standard_indent;

}

}

Return Temp;

}

/ **

* Set Standard_indent before the line (General referring to the air)

* @Param Indent Standard_indent value

* /

Public void setindent (string indent) {

STANDARD_INDENT = Indenter

/ **

* Get an XML string that has been generated. It is valid after the PrintDomtree (Node Node) method

* @Return String

* /

Public string getXmlResult () {

Return Xmlstring;

}

/ **

* Set the starting depth level (directly affecting the number of Standard_indent (spaces) before the line)

* @Param Level level number

* /

Public void setBeginlevel (int level) {

IndentLevel = Level;

}

/ **

* Set the XML header of the XML file

* @Param Header XML file XML header. For example:

* /

Public void setXmlhead (string header) {

XMLHeader = header;

}

/ **

* Setting the wrap defaults to "/ r / n"

* @Param Linseparator wrap split, default "/ r / n"

* /

Public void setLineSeparator (String Linseparator) {

LINESEPARATOR = linesearator;

}

}

The XMloutput.class function is generated with the specified String or InputStream (not necessarily an XML file). code show as below:

Package com.ceic.workflow.xml

Import org.w3c.dom. *;

Import java.io. *;

Import java.util. *;

/ **

* Title: Tools for effective XML strings to generate XML files

* Description: Tools for the effective XML string to generate an XML file

* Copyright: CopyRight (C) 2003

* Company: Guodian Information Center

* @Author Zhang Zhizhong

* @version 1.0

* /

Public class xmloutput {

PRIVATE STRING ObjectPath;

Private string encoding = "utf8";

Public xmloutput () {

}

/ **

* Constructor

* @Param FilePath The target XML file location is generated.

* /

Public XMloutPut (String filepath) {

Objectpath = filepath;

}

/ **

* Set the location of the generated target XML file

* @Param FilePath The target XML file location is generated.

* /

Public void setObjectPath (String filepath) {

Objectpath = filepath;

}

/ **

* Set the encoding format that generates XML files

* @Param Encod Generates an XML file encoding format, default is UTF8

* /

Public void setEncoding (String Encod) {

Encoding = encod;

}

/ **

* Generate an XML file according to the specified xmlstring.

* @Param xmlstring specified XML string

* /

Public void output (string xmlstring) {

IF (! checkObject ()) {

System.out.println ("No specified file to be written");

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 ("write file error");

}

}

/ **

* Generate an XML file according to the specified input stream.

* @Param in specified InputStream

* /

Public void output (InputStream in) {

IF (! checkObject ()) {

System.out.println ("No specified file to be written");

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 ("write file error");

}

}

/ **

* Check if the file PATH is empty

* @Return Boolean

* /

Private boolean checkobject () {

IF (ObjectPath! = Null && ObjectPath.Length ()> 0) Return True;

Return False;

}

}

With these XML operating tools, the next step is to make practical applications. In my previous project (secondary development), there is a legacy issue is the interaction of TREE type permissions and TREE type (including respective maintenance). At that time, the JSP Applet used by the performance layer was implemented which Tree diagram (for the Applet into the file stream of an XML format). The file format is as follows:

"Exit Login" TARGET = "_ TOP" URL = "/ ZDTADMIN / LOGIN.JSP">

"Role Maintenance" Target = "Mainframe" URL = "/ ZDTADMIN / Default.jsp">

"Role <->" Target = "Mainframe" URL = "/ ZDTADMIN / Peradmin

/Role_tree.jsp ">

"Role <-> User" Target = "Mainframe" URL = "/ ZDTADMIN / Peradmin

/role_user.jsp ">

In fact, it is a comparative specification XML document. It is easier to use JSP when there is only two layers of Tree structure. But it is not enough to use JSP when the structure is complicated. In addition, there is permission, the problem is more complicated. After learning the XML and did some of the above work. Decided to use XML (XML to generate a TREE type structure by recursive). code show as below:

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 based = 0;

Private string indent = ""

Private string end = "/ r";

Private string header = "";

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";

PRIVATEATTRING [] nodeattrlist;

Private string collag = "#";

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 Excec) {

System.out.println ("Initialization is invalid, please set the data source by 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 default) {

IF (defaultp! = null && defaultp.Length ()> 0)

DEFAULTPARENT = DefaultP;

}

Public void setMaxTreeElevel (int mapize) {

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 sethead (string header) {

Try {

IF (Header! = null && header.Length ()> 0) {

Header = header;

Tool.SetHeader;

}

} catch (exception e) {

System.out.println ("XMLTool does not exist");

}

}

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 setttrlist (String [] list) {

IF (List.length> 0) {

IF (list.length> maxattrs) Maxattrs = list.length

NodeAtTrlist = NULL;

NodeAtTrlist = new string [maxattrs];

NodeAttrvaluelist = NULL;

Nodettrvaluelist = new string [maxattrs];

Collist.clear ()

For (int i = 0; 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;

Nodettrvaluelist = new string [maxattrs];

mapping.clear ()

For (int i = 0; i

NodeAtTrvaluelist [i] = list [i];

Mapping.put (Collist.ementat (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 && collag.length ()> 0) {

Colflag = colflag;

}

}

Public void setLinend (String LinEnd) {

IF (linend! = 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 ("Initialization Failure");

}

}

Private vidinit () {

Try {

Vec = new int [maxsize];

VEC [0] = 0;

NodeAtTrlist = new string [maxattrs];

Nodettrvaluelist = new string [maxattrs];

NodeaTrlist [0] = "label";

NodeAttrlist [1] = "icon";

NodeAtTrlist [2] = "URL";

NodeaTrlist [3] = "Target";

NodeAtTrlist [4] = "ParentID";

NodeAtTrlist [5] = "ID";

NodettrvaluelIst [0] = COLFLAG "Tree_name";

NodeAttrvaluelist [1] = "/ zdtadmin / images / cluster_folder.gif";

Nodettrvaluelist [2] = COLFLAG "Tree_Address";

nodeattrvaluelist [3] = COLFLAG "Tree_Target"

Defaultflag "_ blank";

NodeAttrvaluelist [4] = COLFLAG "TREE_ID_P";

Nodettrvaluelist [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 ("Initialization Failure");

}

}

Public void createxml () {

Element root = Tool.createElement (rootname);

Doc.Appendchild (root);

Tool.setmarksign (nodename);

Rs.first ()

Mark = 0;

Start = false;

CreateMaPTree (defaultparent, beginlevel, root);

Toool.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);

Toool.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, NOTP);

}

Public void createSelfxmlfile (String Filepath, Boolean NOTOP) {

Tool.Output (filepath, doc.getlementsBytagname

(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.getlementsbytagname (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 (panottreeid) .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 ("Generate Node Failure");

}

}

Private void CreateTreeModel (Node Node, Result Rstemp) {

Try {

// ((Element) node) .SetaTRibute (label, RSTEMP.GETSTRING

// ("Tree_Name"));

// ((Element) .SetaTRibute (icon, icon);

// (Element) .SetaTRibute (URL, RSTEMP.GETSTRING

// ("Tree_Address"));

// if (RSTemp.getstring ("Tree_Target")! = null && rstemp.getstring

// ("Tree_Target"). Length ()> 0) {

// ((Element) .SetaTRibute (target, RSTEMP.

// getString ("Tree_Target");

//}

String Tempattr, TempValue, Tempcol, Tempdefault, TempcolValue

For (int i = 0; i

Tempcol = ""

Tempdefault = ""

TempColValue = "";

Tempattr = Collist.Elementat (i) .tostring ()

Tempvalue = mapping.get (tempattr) .tostring ()

IF (Tempattr! = null && tempattr.length ()> = 0) {

IF (TempValue.indexof (Collag)> = 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 = thistrings.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) .SetaTRibute (Tempattr,

Header TempcolValue;

} else {

(ELEMENT) .SetaTRibute (Tempattribute (Tempattr, TempDefault);

}

} else {

(ELEMENT) .SetaTRibute (Tempattr,

Header TempcolValue;

}

} else {

(ELEMENT) .SetaTRibute (Tempattr, TempValue);

}

}

}

} catch (exception EE) {

Ee.PrintStackTrace ()

System.out.println ("Building Data Failure");

}

}

Public void deletenode (String nodename) {

Tool.delnode (Nodename, NodeName, True);

}

Private Void CreateInDet (int level, node node) {

For (int i = 0; i

Text tx = doc.createtextNode (Indent);

Node.Appendchild (TX);

}

}

Private void move () {

IF (Mark> = 0) {

Rs.first ()

For (int i = 0; i

rs.next ()

}

}

}

Public void close () {

Rs.close ()

}

Private Boolean Checknode (Node Node, String OnType) {

String label = ((Element) node) .getattribute (onepe);

IF (Tool.SetMark (OnePE, 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.AddeElement (DefaultParent);

Return;

} else {

VEC.AddeElement (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

IF (List.Item (i) .Getnodetype () == node.ement_node) {

Tempid = ((Element) List.Item (i)). GetAttribute (Checkone);

IF (Tempid! = Null && Tempid.Length ()> 0) {

VEC.AddeElement (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.setconnetype ("jdbc ");

//rs.setsql ("self * 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.setttrlist(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 = crete.getparents ("30");

// for (int i = 0; i

// system.out.println (Vec.Elementat (i));

//}

//create.deletenode ("id ");

//create.deletenode ("ParentID ");

//create.createserfxmlfile ("D: /tomcat/webapps/test_self.xml" ,true);

//create.close ()

//

//

//

//}

}

Main () is an example. Private Result RS; is a custom recordset, and all records, the object has a "5TOR" is the field name and field value, and there is a field name list vector, there may be any security risks, because I own to Vector, HashTable I don't know very well, I hope that the high-end finger is very well solved by this XML solution, and solve the structure editing in the Tree structure (main benefit is to ensure the integrity of the Tree structure, such as the parent node sleeps. All child nodes are also sleeping, and activation child nodes must ensure that the parent node has been activated.) If there is no XML document structure, these operations will be a complex recursive algorithm, and often operate databases. The last example: Database data and XML file synchronization. code show as below:

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. *;

/ **

*

Title:

*

description:

*

Copyright: CopyRight (c) 2003

*

company:

* @Author unascribed

* @version 1.0

* /

Public class tabletoxml {

Private boolean start = false;

Private result rs;

Private Xmltool Tool;

PRIVATE DOCUMENT. Nbspdoc;

Private int start = 0; private string indent = ""

Private string end = "/ r";

Private string header = "";

Private int maxattrs = 20;

PRIVATE INT MARK = 0;

Private string checkone = "label";

PRIVATEATTRING [] nodeattrlist;

Private string collag = "#";

PRIVATETTRING [] nodeattrvaluel

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 vidinit () {

Try {

NodeAtTrlist = new string [maxattrs];

Nodettrvaluelist = new string [maxattrs];

NodeaTrlist [0] = "label";

NodeAttrlist [1] = "icon";

NodeAtTrlist [2] = "URL";

NodeaTrlist [3] = "Target";

NodeAtTrlist [4] = "ParentID";

NodeAtTrlist [5] = "ID";

NodettrvaluelIst [0] = COLFLAG "Tree_name";

NodeAttrvaluelist [1] = "/ zdtadmin / images / cluster_folder.gif";

Nodettrvaluelist [2] = COLFLAG "Tree_Address";

nodeattrvaluelist [3] = COLFLAG "Tree_Target"

Defaultflag "_ blank";

NodeAttrvaluelist [4] = COLFLAG "TREE_ID_P";

Nodettrvaluelist [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 ("Initialization Failure");

}

}

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 sethead (string header) {

Try {

IF (Header! = null && header.Length ()> 0) {

Header = header;

Tool.SetHeader;

}

} catch (exception e) {

System.out.println ("XMLTool does not exist");

}

}

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 setttrlist (String [] list) {

IF (List.length> 0) {

IF (list.length> maxattrs) Maxattrs = list.length

NodeAtTrlist = NULL;

NodeAtTrlist = new string [maxattrs];

NodeAttrvaluelist = NULL;

Nodettrvaluelist = new string [maxattrs];

Collist.clear ()

For (int i = 0; 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;

Nodettrvaluelist = new string [maxattrs]; mapping.clear ()

For (int i = 0; i

NodeAtTrvaluelist [i] = list [i];

Mapping.put (collist.ementatat (i) .tostring (), N

Odeattrvaluelist [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 && collag.length ()> 0) {

Colflag = colflag;

}

}

Public void setLinend (String LinEnd) {

IF (linend! = 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 results 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, NOTP);

}

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.getlementsbytagname (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 ("Not established still created.

Icon or root element object " 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];

Nodettrvaluelist = new string [maxattrs];

}

IF (Collist! = null) {collist.removeallelements () collist.

Clear ()}

IF (mapping! = null) {mapping .clear ()}

For (int K = 0; k

NodeAttrlist [k] = vec.ementatat (k) .tostring ()

NodeAttrvaluelIst [K] = COLFLAG NodeAtTrlist [k];

Collist.addelement (nodeattrlist [k]);

Mapping.put (nodeattrign [k], nodeattrvaluelist [k]);

}

}

Mark = 0;

Start = false;

CreatemapTree (Beginlevel, Root, Checkone);

Toool.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.GtelementsBytagname (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];

Nodettrvaluelist = new string [maxattrs];

}

IF (Collist! = null) {collist.removeallelements ()

Collist .clear ()}

IF (mapping! = null) {mapping .clear ()}

For (int K = 0; k

NodeAttrlist [k] = vec.ementatat (k) .tostring ()

NodeAttrvaluelIst [K] = COLFLAG NodeAtTrlist [k];

Collist.addelement (nodeattrlist [k]);

Mapping.put (nodeattrign [k], nodeattrvaluelist [k]);

}

}

Mark = 0;

Start = false;

CreatemapTree (Beginlevel, Root, Checkone);

Toool.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 ("Generate Node Failure");

}

}

Private void CreateTreeModel (Node Node, Result Rstemp) {

Try {

// ((Element) node) .SetaTRibute (label, RSTEMP.GETSTRING

// ("Tree_name")); // ((Element) node) .SetaTRibute (icon, icon);

// (Element) .SetaTRibute (URL, RSTEMP.GETSTRING

// ("Tree_Address"));

// if (RSTemp.getstring ("Tree_Target")! = null && rstemp.getstring

// ("Tree_Target"). Length ()> 0) {

// (Element) .SetaTAttribute (target, RSTEMP.GETSTRING

// ("Tree_Target"));

//}

String Tempattr, TempValue, Tempcol, Tempdefault, TempcolValue

For (int i = 0; i

Tempcol = ""

Tempdefault = ""

TempColValue = "";

Tempattr = Collist.Elementat (i) .tostring ()

Tempvalue = mapping.get (tempattr) .tostring ()

IF (Tempattr! = null && tempattr.length ()> = 0) {

IF (TempValue.indexof (Collag)> = 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) .SetaTRibute (Tempattr,

Header TempcolValue;

} else {

(ELEMENT) .SetaTRibute (Tempattribute (Tempattr, TempDefault);

}

} else {

(ELEMENT) .SetaTRibute (Tempattr,

Header TempcolValue;

}

} else {

(ELEMENT) .SetaTRibute (Tempattr, TempValue);

}

}

}

} catch (exception EE) {

Ee.PrintStackTrace ()

System.out.println ("" Building data failed, possible reason is the specified node value

The fields in the list are used in the fields that cannot be acquired. ");

}

}

Public void deletenode (String nodename) {

Tool.delnode (Nodename, Nodename, True);

Private Void CreateInDet (int level, node node) {

For (int i = 0; i

Text tx = doc.createtextNode (Indent);

Node.Appendchild (TX);

}

}

Public void close () {

IF (rs! = null) rs.close ()

}

Private Boolean Checknode (Node Node, String OnType) {

String label = ((Element) node) .getattribute (onepe);

IF (Tool.SetMark (OnePE, 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"};

/ / # Begins to read the value of the specified field name, @ followed by the # field name reading no value or NULL

// The default value can be made in a simple combination. For example: "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.SetaTRList (name);

TTX.SetValuelist (Value);

// ttx.setencoding ("GBK");

TTX.SetHeader ("");

Ttx.createxml (False, False);

// The first parameter is whether all fields in SQL may otherwise use the specified field and a list of values.

// The second parameter refers to whether or not to check the uniqueness. Through TTX.SetCheckone (String STR)

// Set the unique field.

TTX.setrootattr ("Name", "cm_tree");

Ttx.createxmlfile ("D: //xmlteest//example//ttx2.xml");

TTX.Close ()

System.out.println (TTX.GETXMLSTRING (TRUE));

}

}

转载请注明原文地址:https://www.9cbs.com/read-68240.html

New Post(0)