Dom4j operation XML (including encapsulation and parsing)

Source: Internet
Author: User
Tags addchild
Dom4j operation XML (including encapsulation and parsing)

Let's take a look at the inheritance relationships established by the DOM tree corresponding to XML in dom4j.

 


For the XML standard definition that corresponds to the content listed in Figure 2-1, dom4j provides the following implementation:

 


The following is an example:
Package com. iboxpay. Settlement. Gateway. Common. util;

Import java. Io. ioexception;
Import java. Io. stringreader;
Import java. Io. stringwriter;

Import org. dom4j. Document;
Import org. dom4j. extends entexception;
Import org. dom4j. documenthelper;
Import org. dom4j. element;
Import org. dom4j. Io. outputformat;
Import org. dom4j. Io. saxreader;
Import org. dom4j. Io. xmlwriter;

Import com. iboxpay. Settlement. Gateway. CCB. constant;
Import com. iboxpay. Settlement. Gateway. Common. Exception. packmessageexception;
Import com. iboxpay. Settlement. Gateway. Common. Exception. parsemessageexception;

/**
* Dom4j tool class
* @ Author caolipeng
*/
Public class domutil {
/**
* Add child node Elements
* @ Param parent node
* @ Param childname child node name
* @ Param childvalue child node Value
* @ Return Add a node
*/
Public static element addchild (element parent, string childname,
String childvalue ){
Element child = parent. addelement (childname); // Add a node Element
Child. settext (childvalue = NULL? "": Childvalue); // set the value for the element
Return child;
}
/**
* Convert the Document Object of dom4j to an XML message string.
* @ Param document
* @ Param charset
* @ Return the parsed XML string
*/
Public static string documenttostring (document, string charset ){
Stringwriter = new stringwriter ();
Outputformat format = outputformat. createprettyprint (); // get the formatted output stream
Format. setencoding (charset); // sets the character set, which defaults to the UTF-8
Xmlwriter = new xmlwriter (stringwriter, format); // write a file stream
Try {
Xmlwriter. Write (document );
Xmlwriter. Flush ();
Xmlwriter. Close ();
} Catch (ioexception e ){
Throw new runtimeexception (E );
}
Return stringwriter. tostring ();
}
/**
* Remove the Declaration header (that is, <? XML...?> Remove)
* @ Param document
* @ Param charset
* @ Return
*/
Public static string documenttostringnodeclaredheader (document, string charset ){
String xml = documenttostring (document, charset );
Return XML. replacefirst ("\ s * <[^ <>] +> \ s *","");
}
/**
* Parse XML as a Document Object
* @ Param XML the parsed XML
* @ Return document
* @ Throws parsemessageexception
*/
Public final static element parsexml (string XML) throws parsemessageexception {
Stringreader sr = new stringreader (XML );
Saxreader = new saxreader ();
Document document;
Try {
Document = saxreader. Read (SR );
} Catch (incluentexception e ){
Throw new parsemessageexception (E );
}
Element rootelement = Document. getrootelement ();
Return rootelement;
}

Public final static string gettext (Element E, string tag ){
Element _ e = E. element (TAG );
If (_ e! = NULL)
Return _ E. gettext ();
Else
Return NULL;
}
Public final static string gettexttrim (Element E, string tag ){
Element _ e = E. element (TAG );
If (_ e! = NULL)
Return _ E. gettexttrim ();
Else
Return NULL;
}
/**
* Get the node value. The node must not be blank; otherwise, an error is thrown.
* @ Param parent
* @ Param tag
* @ Return
* @ Throws parsemessageexception
*/
Public final static string gettexttrimnotnull (element parent, string tag) throws parsemessageexception {
Element E = parent. element (TAG );
If (E = NULL)
Throw new parsemessageexception (parent. getname () + "->" + tag + "node is empty .");
Else
Return e. gettexttrim ();
}
/**
* The node must not be blank; otherwise, an error is thrown.
* @ Param parent
* @ Param tag
* @ Return
* @ Throws parsemessageexception
*/
Public final static element elementnotnull (element parent, string tag) throws parsemessageexception {
Element E = parent. element (TAG );
If (E = NULL)
Throw new parsemessageexception (parent. getname () + "->" + tag + "node is empty .");
Else
Return E;
}
Public static void main (string [] ARGs) throws packmessageexception, parsemessageexception {
Document document = incluenthelper. createdocument ();
Document. setxmlencoding ("gb2312 ");
Element root = Document. addelement ("TX ");
Domutil. addchild (root, "request_sn", "bankbatchseqid ");
Domutil. addchild (root, "cust_id", "cust_id ");
Domutil. addchild (root, "user_id", "user_id ");
Domutil. addchild (root, "password", "password ");
Domutil. addchild (root, "tx_code", "txcode ");
Domutil. addchild (root, "language", "cn ");
Element tx_info = root. addelement (constant. tx_info );
Domutil. addchild (tx_info, constant. request_sn1, "request_sn1 ");
String xml = domutil.doc umenttostringnodeclaredheader (root. getdocument (), "GBK ");
System. Out. println (XML );
Root = parsexml (XML );
System. Out. println (root. element ("tx_info"). elementtext ("request_sn1 "));
}
}
The main function test result is:
<TX>
<Request_sn> bankbatchseqid </request_sn>
<Cust_id> cust_id </cust_id>
<User_id> user_id </user_id>
<Password> password </password>
<Tx_code> txcode </tx_code>
<Language> CN </language>
<Tx_info>
<Request_sn1> request_sn1 </request_sn1>
</Tx_info>
</TX>

Request_sn1


Blog references: http://www.cnblogs.com/macula/archive/2011/07/27/2118003.html

Dom4j operation XML (including encapsulation and parsing)

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.