Java operation XML (using org. W3C. DOM)

Source: Internet
Author: User

1. Create a DOM

Xmlbuilder. java is used to create the Dom, root Node /************************************* * ******************************** Project name: rochoc <p> * package name: rochoc. XML. compile <p> * file name: xmlbuilder <p> * Writer: luoc <p> * Writing Date: 2005-6-22 <p> * program function (class) Description: generate document and root nodes based on the imported XML file <p> ** program change date: * Author: * description of changes: **************************************** * ***************************/package rochoc. XML. imports; import Java. io. file; import Java. io. ioexception; import javax. XML. parsers. documentbuilder; import javax. XML. parsers. documentbuilderfactory; import javax. XML. parsers. parserconfigurationexception; import Org. apache. log4j. logger; import Org. w3C. dom. document; import Org. w3C. dom. element; import Org. XML. sax. saxexception;/*** Class Name: xmlbuilder <p> * class description: generate the document and root nodes based on the imported XML file <p> * Prepared: luoc <p> * written on: 2005-6-22 <p> * main public member variables: <p> * Main public method: <p> **/public class xmlbuilder {/*** constructor Description: <p> * parameter description: @ Param path <p> **/Public xmlbuilder (string path) {This. path = path; Init ();}/*** Method Name: init <p> * method function: initialization function <p> * parameter description: <p> * return: void <p> * Author: luoc * Date: 2005-6-22 **/Public void Init () {builddocument (); buildroot ();}/*** Method Name: builddocument <p> * method function: generate document from XML file <p> * parameter description: <p> * return: void <p> * Author: luoc * Date: 2005-6-22 **/ Private void builddocument () {documentbuilderfactory factory = documentbuilderfactory. newinstance (); try {documentbuilder builder = factory. newdocumentbuilder (); logger. debug ("construct document builder success. "); Doc = builder. parse (new file (PATH); logger. debug ("build XML document success. ");} catch (parserconfigurationexception e) {logger. error ("construct document builder error:" + E);} catch (saxex Ception e) {logger. error ("Parse XML file error:" + E);} catch (ioexception e) {logger. error ("read XML file error:" + E) ;}/ *** Method Name: buildroot <p> * method function: generate xml root node <p> * parameter description: <p> * return: void <p> * Author: luoc * Date: 2005-6-22 **/private void buildroot () {root = Doc. getdocumentelement ();}/*** @ return returns the doc. */Public document getdoc () {return Doc;}/*** @ Param Doc the doc to be set. */Public void setdoc (document DOC) {this.doc = Doc;}/*** @ return returns path. */Public String getpath () {return path;}/*** @ Param path the path to be set. */Public void setpath (string path) {This. Path = path;}/*** @ return returns root. */Public element getroot () {return root;}/*** @ Param root the root to be set. */Public void setroot (element root) {This. root = root;}/* global variable */private string Path = NULL; // XML file path private document DOC = NULL; // document private element root = NULL for the XML file; // The root node of the XML file private logger = logger. getlogger (getclass (). getname ());}

2. Search, insert, delete, and modify

Xmloper. java is used to operate XML files, including searching, adding, deleting, and modifying nodes /****************************** * ************************************ Project name: rochoc <p> * package name: rochoc. XML. compile <p> * file name: xmloper <p> * Prepared by: luoc <p> * written on: 2005-6-22 <p> * program function (class) Description: perform read and write operations on XML <p> ** program change date: * Author: * Change description: **************************************** * ***************************/package rochoc. XML. imports; import Java. util. arraylist; import Org. apache. log4j. logger; import Org. w3C. dom. document; import Org. w3C. dom. element; import Org. w3C. dom. node; import Org. w3C. dom. nodelist;/*** Class Name: xmloper <p> * class description: read/write operations on XML files, all static functions <p> * Prepared: luoc <p> * Writing Date: 2005-6-22 <p> * main public member variable: <p> * main public method: <p> **/public class xmloper {/*** constructor Description: <p> * parameter description: <p> **/private xmloper () {}/*** Method Name: getnodelist <p> * method function: obtains all child nodes of the parent node parent. <p> * parameter description: @ Param parent * parameter description: @ return <p> * return: nodelist <p> * Author: luoc * Date: 2005-6-22 **/public static nodelist getnodelist (element parent) {return parent. getchildnodes ();}/*** Method Name: getelementsbyname <p> * method function: query the node set with the specified name in the parent node <p> * parameter description: @ Param parent * parameter description: @ Param name * parameter description: @ return <p> * return: Element [] <p> * Author: luoc * Date: 2005-6-22 **/public static element [] getelementsbyname (element parent, string name) {arraylist reslist = new arraylist (); nodelist NL = getnodelist (parent ); for (INT I = 0; I <NL. getlength (); I ++) {node nD = NL. item (I); If (Nd. getnodename (). equals (name) {reslist. add (ND) ;}} element [] res = new element [reslist. size ()]; for (INT I = 0; I <reslist. size (); I ++) {res [0] = (element) reslist. get (I);} logger. debug (parent. getnodename () + "'s children of" + name + "'s num:" + Res. length); Return res;}/*** Method Name: getelementname <p> * method function: get the name of the specified Element <p> * parameter description: @ Param element * parameter description: @ return <p> * return: String <p> * Author: luoc * Date: 2005-6-22 **/public static string getelementname (element) {return element. getnodename ();}/*** Method Name: getelementvalue <p> * method function: Get the value of a specified Element <p> * parameter description: @ Param element * parameter description: @ return <p> * return: String <p> * Author: luoc * Date: 2005-6-22 **/public static string getelementvalue (element) {nodelist NL = element. getchildnodes (); For (INT I = 0; I <NL. getlength (); I ++) {If (NL. item (I ). getnodetype () = node. text_node) // is a text node {logger. debug (element. getnodename () + "has a text node. "); Return element. getfirstchild (). getnodevalue () ;}} logger. error (element. getnodename () + "hasn' t a text node. "); return NULL;}/*** Method Name: getelementattr <p> * method function: gets the ATTR value of the attribute of the specified Element <p> * parameter description: @ Param element * parameter description: @ Param ATTR * parameter description: @ return <p> * return: String <p> * Author: luoc * Date: 2005-6-22 **/public static string getelementattr (element, string ATTR) {return element. getattribute (ATTR);}/*** Method Name: setelementvalue <p> * method function: set the value of a specified Element <p> * parameter description: @ Param element * parameter description: @ Param Val <p> * return: void <p> * Author: luoc * Date: 2005-6-22 **/public static void setelementvalue (element, string Val) {node = element. getownerdocument (). createtextnode (VAL); nodelist NL = element. getchildnodes (); For (INT I = 0; I <NL. getlength (); I ++) {node nD = NL. item (I); If (Nd. getnodetype () = node. text_node) // is a text node {nd. setnodevalue (VAL); logger. debug ("modify" + element. getnodename () + "'s node value succe. "); Return ;}} logger. debug ("new" + element. getnodename () + "'s node value succe. "); element. appendchild (node);}/*** Method Name: setelementattr <p> * method function: Set the attribute of the node element <p> * parameter description: @ Param element * parameter description: @ Param ATTR * parameter description: @ Param attrval <p> * return: void <p> * Author: luoc * Date: 2005-6-22 **/public static void setelementattr (element, string ATTR, string attrval) {element. setattribute (ATTR, attrval);}/*** Method Name: addelement <p> * method function: Add node child under parent <p> * parameter description: @ Param parent * parameter description: @ Param child <p> * return: void <p> * Author: luoc * Date: 2005-6-22 **/public static void addelement (element parent, element child) {parent. appendchild (child);}/*** Method Name: addelement <p> * method function: add the node generated by the string tagname under the parent <p> * parameter description: @ Param parent * parameter description: @ Param tagname <p> * return: void <p> * Author: luoc * Date: 2005-6-22 **/public static void addelement (element parent, string tagname) {document DOC = parent. getownerdocument (); element child = Doc. createelement (tagname); parent. appendchild (child);}/*** Method Name: addelement <p> * method function: add the text node of tagname under parent, and the value is text <p> * parameter description: @ Param parent * parameter description: @ Param tagname * parameter description: @ Param text <p> * return: void <p> * Author: luoc * Date: 2005-6-22 **/public static void addelement (element parent, string tagname, string text) {document DOC = parent. getownerdocument (); element child = Doc. createelement (tagname); setelementvalue (child, text); parent. appendchild (child);}/*** Method Name: removeelement <p> * method function: Remove a node named tagname under the parent node. <p> * parameter description: @ Param parent * parameter description: @ Param tagname <p> * return: void <p> * Author: luoc * Date: 2005-6-22 **/public static void removeelement (element parent, string tagname) {logger. debug ("Remove" + parent. getnodename () + "'s children by tagname" + tagname + "begin... "); nodelist NL = parent. getchildnodes (); For (INT I = 0; I <NL. getlength (); I ++) {node nD = NL. item (I); If (Nd. getnodename (). equals (tagname) {parent. removechild (ND); logger. debug ("remove child" + Nd + "'success. ") ;}} logger. debug ("Remove" + parent. getnodename () + "'s children by tagname" + tagname + "end. ");}/* global variable */static logger = logger. getlogger ("xmloper ");}

3. Create an XML file

Xmlcreater. java is used to create an XML file /********************************** * *********************************** Project name: rochoc <p> * package name: rochoc. XML. compile <p> * file name: xmlcreater <p> * Prepared by: luoc <p> * written on: 2005-6-22 <p> * program function (class) Description: create Dom and generate xml file <p> ** program change date: * Change Author: * Change description: **************************************** * ***************************/package rochoc. XML. imports; import Java. io. file; import javax. XML. parsers. Documentbuilder; import javax. XML. parsers. documentbuilderfactory; import javax. XML. parsers. parserconfigurationexception; import javax. XML. transform. transformer; import javax. XML. transform. transformerconfigurationexception; import javax. XML. transform. transformerexception; import javax. XML. transform. transformerfactory; import javax. XML. transform. dom. domsource; import javax. XML. transform. stream. streamresult; Import Org. apache. log4j. logger; import Org. w3C. dom. document; import Org. w3C. dom. element;/*** Class Name: xmlcreater <p> * class description: Creates a Dom and generates an XML file <p> * Writer: luoc <p> * Writing Date: 2005-6-22 <p> * main public member variables: <p> * main public method: <p> **/public class xmlcreater {/*** constructor description: <p> * parameter description: @ Param path: XML file path <p> **/Public xmlcreater (string path) {This. path = path; Init ();}/*** Method Name: init <p> * method function: initialization function <p> * parameter description: <p> * return: Void <p> * Author: luoc * Date: 2005-6-22 **/private void Init () {documentbuilderfactory factory = documentbuilderfactory. newinstance (); try {documentbuilder builder = factory. newdocumentbuilder (); Doc = builder. newdocument (); // new Dom} catch (parserconfigurationexception e) {logger. error ("parse Dom builder error:" + E) ;}/ *** Method Name: createrootelement <p> * method function: Create a root node, <p> * parameter description: @ Param roottagname <p> * is returned: Element <p> * Author: luoc * Date: 2005-6-22 **/public element createrootelement (string roottagname) {If (Doc. getdocumentelement () = NULL) {logger. debug ("create root element" + roottagname + "'success. "); element root = Doc. createelement (roottagname); Doc. appendchild (Root); Return root;} logger. warn ("this Dom's root element is exist, create fail. "); Return Doc. getdocumentelement ();}/*** Method Name: createelemen T <p> * method function: add a sub-node tagname under the parent node <p> * parameter description: @ Param parent * parameter description: @ Param tagname <p> * return: element <p> * Author: luoc * Date: 2005-6-22 **/public element createelement (element parent, string tagname) {document DOC = parent. getownerdocument (); element child = Doc. createelement (tagname); parent. appendchild (child); return child;}/*** Method Name: createelement <p> * method function: tabname <p> * parameter description: @ Param Parent * parameter description: @ Param tagname * parameter description: @ Param value <p> * return: Element <p> * Author: luoc * Date: 2005-6-22 **/public element createelement (element parent, string tagname, string value) {document DOC = parent. getownerdocument (); element child = Doc. createelement (tagname); xmloper. setelementvalue (child, value); parent. appendchild (child); return child;}/*** Method Name: createattribute <p> * method function: Add attribute under the parent node <p> * parameter description: @ Param parent * parameter description: @ Param attrname attribute name * parameter description: @ Param attrvalue attribute value <p> * return: void <p> * Author: luoc * Date: 2005-6-22 **/Public void createattribute (element parent, string attrname, string attrvalue) {xmloper. setelementattr (parent, attrname, attrvalue);}/*** Method Name: buildxmlfile <p> * method function: generate an XML file based on Dom <p> * parameter description: <p> * return: void <p> * Author: luoc * Date: 2005-6-22 **/Public void buildxmlfile () {transformerfactory Tfactory = transformerfactory. newinstance (); try {transformer = tfactory. newtransformer (); domsource source = new domsource (DOC); logger. debug ("New domsource success. "); streamresult result = new streamresult (new file (PATH); logger. debug ("New streamresult success. "); transformer. setoutputproperty ("encoding", "GBK"); transformer. transform (source, result); logger. debug ("build XML file '" + path +" 'Success. ");} catch (transformerconfigurationexception e) {logger. error ("create transformer error:" + E);} catch (transformerexception e) {logger. error ("transformer XML file error:" + E) ;}/ *** @ return returns the doc. */Public document getdoc () {return Doc;}/*** @ Param Doc the doc to be set. */Public void setdoc (document DOC) {this.doc = Doc;}/*** @ return returns path. */Public String getpath () {return path;}/*** @ Param path the path to be set. */Public void setpath (string path) {This. path = path;}/* global variable */private logger = logger. getlogger (getclass (). getname (); private document DOC = NULL; // the newly created Dom private string Path = NULL; // The generated XML file absolute path}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.