How to easily manipulate data in XML (Java code implementation)

zhaozj2021-02-17  34

/ ****************************************** Program: Chen Linmao * write date: 2003-03-16 * Contact the author: linmaochen@sohu.com********************************** ********* /

As we all know, XML is very hot in the current web application, but in the program, how do we control?

Data in XML, how to combine your XML data, is indeed a troublesome problem, in the example below

I will introduce some of my solutions to everyone:

1. First, please see the two XML files below:

Struct.xml is a specific structure description of data information;

Employees.xml: The specific XML data information is used.

Here is the specific XML text content: struct.xml:

Empno 1 4 > FirstName 1 8 Lastname 1 8 8 Phoneext 1 20 HiRedate 3 10 Deptno 1 10 < Field> Jobcode 1 10 Jobgrade 1 < Fieldsize> 10 JobCountry 1 20 Salary 4 20 <

Field> Fullname 1 30 ------------------------------------------------------------------ -------------------------------------------------- ----------------- Employees.xml 2 Robert Nelson 250 1988-12-28 600 VP 2 USA 105900.000000 Nelson, Robert 4 Bruce < / Firstname> YOUNG 233 1988-12-28 621 eng 2 USA 97500.000000 Young, Bruce 5 Kim Lambert 22 < / Phoneext> 1989-02-06 130 English 2 USA 102750.000000 Lambert, kim

2. For good and very intuitive manipulating XML data, we will simulate a component similar to the Query in Delphi, due to the space, here only provides its simple implementation: it will include three basic Java classes: Xfield.java Description Class of Single Field Information; Xfields.java Single Record Description Class; XQuery.java is similar to the control of Query's query class. The following is the three-class concrete source code: / ** *

Title: Field Unit *

Description: Memory Record In Field Information Description *

Copyright: CopyRight (C) 2002 *

Company: * @Author Chen Linmao 2003-03-12 * @version 1.0 * /

Import java.lang. *; import java.lang.double;

/ * * Describe the field information in the memory record * /

/ ************************************************** ******* log: * 2003-03-12: Add xfield ******************************************** *********************** /

Public class xfield {

/ * * Field type Description: * ftinteger: integer field * ftstring: string field * ftdte: Date type field * ftfloat: floating point field information * / private static int ftinteger = 2; private static INT fTDATE = 3; private static int ftfloat = 4;

/ ****************************************************************** / Private String FieldName; private int fieldType; private string FieldValue; private int fieldsize = 0;

Public xfield () {}

Public Xfield (String FldName) {FieldName = FldName;}

Public Xfield (String FldName, Int FldType) {FieldName = FldName; FieldType = fldType;}

Public Xfield (String FldName, Int FldType, String FldValue) {FieldName = FldName; FieldType = fldType; FieldValue = FldValue;}

/ / Get the name of the field public string getfieldname () {return this.fieldname;}

/ / Get the category of the field public int getfieldtype () {return fieldType;}

// Setting the category of the field public void setfieldType (int sfieldtype) {this.fieldType = sfieldType;}

// Setting the length of the field public void setfieldsize (int size) {this.fieldsize = sside;}

/ / Get the integer value of the current field public int getasinteger () {if (isinteger (FieldValue) Return Integer.Parseint (FieldValue); Return 0;} // Get the string of the current field PUBLIC STRING GETASSTRING () {

Return FieldValue;}

/ / Get the floating-point value of the current field public double getasfloat () {if (isfloat (FieldValue)) {returnction.parsedouble (FieldValue);} return 0.0;}

// Set the value of the field public void setfieldValue (string sfldvalue) {this.fieldValue = sfldValue;}

/ * * Determined whether a field value is an integer * / private boolean isinteger (String Numstr) {INT i = 0; for (i = 1; i

IF ((Numstr.Charat (i) <= '0') || (Numstr.Charat (i)> = '9')) {RETURN FALSE

}}} Return True;}

/ * * Determine if a field value is a floating point * / private boolean isflloat (String Numstr) {INT i = 0; for (i = 1; i = '9')) {return false;}}} return

/ * * Judging whether a field value is a date * / private boolean isdatetime (String DateStr) {// to do

Return True;}

}

/ ** *

Title: Memory single record information class *

Description: Memory record single record information description *

Copyright: CopyRight (c) 2002 *

company: * @Author Chen Linmao 2003-03-13 * @version 1.0 * /

Import java.util. *; import java.lang. *; import excelsample.xfield;

/ ** Xfields class is combined with some field information, * thus combines a single record message * which provides the following features: * 1: Find a field message * 2: Reset a field value * /

Public class xfields {

// Field Information Container Private Vector Vector = New Vector (100);

Public xfields () {}

// Add a field information public void addxfield (xfield sfld) {vector.add (sfld);} // remove a field information public void Removexfield (xfield sfld) {if (Vector.Size ()> 0) Vector.remove (sfld);

/ / Return to the number of pUBLIC INT getCount () {return vector.size ();}

/ / Get a field information according to the name Public Xfield getFieldByname (String sfldname) {INT i; int pos; xfield xfield; for (i = 0; i = 0) {Return Xfield;}

} Return NULL;}

/ / Get a field information according to the serial number PUBLIC XFIELD GETFIELD (INTOR.SIZE ()> index) Return (Xfield); Return NULL;}

// Copy a field message public xfield copyfield (int index) {xfield sfield; if (this.vector.size ()> index) {

Sfield = (xiEld); xfield xfield = new xfield (sfield.getfieldname (), sfield.getfieldType (), sfield.getastring ());

Return Xfield;

Return NULL;

}

/ ** *

Title: Memory Recorder *

Description: Store record information provided in the XML file into memory *

Copyright: CopyRight (C) 2002 < / p> *

Company: * @AUTHOR Chen Linmao 2003-03-15 * @version 1.0 * /

/ * * Name of the class: xQuery * Description: This class will simulate a structure information similar to Delphi Query; * 1. It provides recorded lookups, moves to the first record, moved to the next record or the like; * 2. It also includes structural and data information * 3. Use it easy to retrieve data in memory * /

Import java.lang. *; import java.util. *;

Public class xquery {

// Memory Record Container Private Vector Vector = New Vector (100); // Memory Recording Structure Information Private Xfields Struct = NULL;

// Whether to go to the end of the record private boolean receivedof = true;

// Currently operated record private xfields currxfields = NULL;

// Current record number private int reccNo = 0;

Public xquery () {

}

/ / Set the structure information of the memory record PUBLIC VOID SetSturcture (Xfields SSTRUCT) {this.struct = SSTRUCT;}

// Add a record information public void addrecord (xfields xfields) {vector.add (xfields);

// Remove the information of the message Public void RemoveRecord (Xfields Xfields) {if (Vector.Size ()> 0) Vector.Remove (Xfields);

// Get the total number of records of the current record set public int getRecordcount () {return vector.size ();

/ * * Related action function * /

// Move to the first record public void first () {if (Vector.Size () <= 0) {this.receof = true; return;

Currxfields = (xfields) (Vector.ementat (0)); this.receof = false; this.Recno = 0;}

// Move to the next record public void next () {if (vector.size () == (this.Recno 1)) {this.ReceOf = true; this.currxfields = null; return;}

THIS.RECNO = this.Recno 1; this.currxfields = (xfields) (this.Recno); this.ReceOf = false;}

// Add a blank record information public void insertRecord () {INT i = 0; xfields xfields = new xfields ();

For (i = 0; i

/ / Get the number of fields in the record set PUBLIC INT getfieldscount () {return this.struct.getcount ();

// Return the current record of the record PUBLIC XFIELDS Recordset () {Return this.currxfield;

/ / Judgment the record set to the end public boolean EOF () {Return this.ReceOf;}

}

3. Finally, tell you how to read how to read the data in XML and put it in the XQuery class. Please see the specific implementation: (1) Establish a class parsing the XML file (see JBuilder " Example):

Import java.io.ioException; import org.xml.sax. *; import org.xml.sax.helpers. *; import org.apache.xerces.parsers.saxparser;

Public class xmlparser extends defaulthandler {

Private static int indent = 4; private static string attlist = "";

// Record table information public static xquery query = new xquery ();

// Record structure information public xfields xfields = new xfields ();

// Temporary Field Information Private Xfield Xfield = Null; Private String ElementName = ""

/ * Resolution Behavior: * 0: Resolve the information in the XML file to the structure definition information of the record table * 1: Resolve the information in the XML file as the specific record information of the record table * / private static int parsemode = 0; private int idx = 0;

Public void character, intlene, throws saxception {string s = new string (ch, start, length); if (CH [0] == '/ n') return; system.out. Println (Getindent () "Value:" S); if (this.Parsemode == 0) {if (this.ElementName.indexof ("FieldName")> = 0) {this.xfield = new xfield (s) System.out.println ("FieldName IS:" this.xfield.getfieldName ());}

IF ("FieldType"> = 0) {if (this.xfield! = null) {Try {this.xfield.setfieldType (Integer.Parseint (s)); system.out.println (" FIELDTYPE IS: " this.xfield.getfieldType ());} catch (exception e) {E.PrintStackTrace ();}}

}

IF ("FieldSize"> = 0) {if (this.xfield! = null) {this.parseint (s)); // Add a field definition this.xfields .Addxfield (this.xfield); System.out.println ("Record Fields Count Is:" this.xfields.getcount ());}}}

// if (this.Parsemode == 1) {this.query.recordset (). Getfieldbyname (this.elementname) .SetfieldValue (s);}

} Public void enddocument () throws saxception {idx - = indent; system.out.println (getindent () "end document"); System.out.Println ("... Parsing Ends"); if (this.Parsemode == 0) this.Query.setSturcture (this.xfields);

} Public void endElement (String uri, String localName, String qName) throws SAXException {if "(Attributes:" attList; attList = "(attList.equals (" System.out.println getIndent () ) ")!)" System.out.println (getindent () "end document"); idx - = indent; system.out.println ("The idx is:" string.valueof (idx));} public void startdocument () THROWS SAXEXCEPTION {IDX = 0; IDX = Indenter; system.out.println ("Parsing Begins ..."); System.out.println (Getindent () "Start Document:")

} Public void startElement (String uri, String localName, String qName, Attributes attributes) throws SAXException {idx = INDENT; System.out.println ( '/ n' getIndent () "start element:" localName); if ()> 0) {IDX = indent; for (int i = 0; i = 0) IF (idx == 12) {this.Query.insertRecord () } Break;}}

Private string getindent () {stringbuffer sb = new stringbuffer (); for (int i = 0; i

Public Static void setQuery (xquery sxquery) {query = SXQUERY;

// Set the identification mode public static void setmode (int smode) {PARSEMODE = Smode;}

}

(2) How to read data from XML and put it in XQuery, and free operation data: / ** *

Title: Excel file information write class *

description: from Read the information in an XML file and write into the Excel file to go to *

Copyright: Copyright (c) 2002 *

Company: * @Author Chen Linmao 2003- 03-15 * @version 1.0 * /

/ * * Excel record write demo * Description: It is mainly divided into three steps: * 1 Read the struct.xml file, establish the recorded field structure information; * 2 ​​Read the replard.xml file, get specific record information; * 3 Write the information to the Excel file * / Import java.io.file; import java.util.date; import jxl. *; // For Excel open source support class IMPORT JXL.WRITE. *; Import Java. IO.IOEXCEPTION; Import Org.xml.sax. *; import org.xml.sax.helpers. *; import org.apache.xerces.Parsers.saxparser;

Public class excelwrite {

Public Excelwrite () {}

Public static void main (String Argv []) {

IF (argv.Length! = 3) {system.out.println ("The Application Argument IS" "Java Excelwrite [struct.xml] [RECORD.XML] [OUTPUT.XLS]"); System.exit (-1 }

String structfile = argv [0]; String Recordfile = argv [1]; string outputfile = argv [2]; int i = 0; int m = 0; xquery squery = new xquery ();

// Establish memory record information TRY {

// Create an XML parser XMLReader parser = XMLReaderFactory.createXMLReader ( "org.apache.xerces.parsers.SAXParser"); xmlParser MySaxParserInstance = new xmlParser (); xmlParser.setQuery (sQuery); parser.setContentHandler (MySaxParserInstance);

// Resolution of the structure information of the record set XMLParser.SetMode (0); Parser.Parse (STRUCTFILE); System.out.Println ("The RecordSet Fields Count Is:" SQuery.Getfieldscount ());

// Analyze the data information of the recordset XMLParser.SetMode (1); Parser.Parse (Recordfile); System.out.Println ("The Recordset Record Count IS: SQuery.getRecordCount ());} catch (ooException ie) {IOE.PrintStackTrace ();} catch (saxException SAXE) {SAXE.PRINTSTACKTRACE ();

// Start writing data information try {// Establish an Excel file write class WritableWorkbook Workbook = Workbook.createworkbook (new file (outputfile);

// Establish a workbook Writablesheet Sheet = Workbook.createsheet ("Employee Record Data", 0); // Establishing the title information of each column, manipulating data string s = ""; for (i = 0; i)

// Write the data to filework.write (); workbook.close ();

} catch (exception e) {E.PrintStackTrace ();

}

4. Summary: First establish the original record information of the record, divide two XML files, one of which is a specific structure of the data, and the other is a specific data information; and then build a class similar to Query, it can easily control the memory Data information (including the upward movement of the record, etc.); Next, establish an XML parser, first resolve the structure information, and initialize the specific XQuery class;

Then parse data information and populate data information into XQuery.

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

New Post(0)