Key words: XPath, JDOM When using JDOM to parse XML documents, we often need to quickly locate a node for reading or modifying operations. Locate the node. This is where the XPath expression works. Since Beta 9 (downloaded from www.jdom.org), JDOM supports parsing XPath path expressions, which makes it much easier for us to use JDOM to parse XML documents. See the example 1. The example uses an XML file, KK. xml <? XML version = "1.0" encoding = "gb2312"?> <Contact list> <Contact> <Name> Zhang San </Name> <ID> 001 </ID> <Company> Company A </company> <Email> zhang@aaa.com </Email> <Phone number type = "company"> (010) 62345678 </phone number> <Phone number type = "family"> (010) 88888888 </phone number> <Address> <Street> No. 1234 Fifth Street </street> <City> Beijing </city> <Province> Beijing </province> </Address> </Contact> Li Si 002 Company B li@bbb.org (021) 87654321 No. 9876 Nanjing Road Shanghai Shanghai 2. To find the phone number of Michael Jacob's family, use the followingCodeSegment Package test; Import java. util. List; Import java.net. url; Import org. JDOM .*; Import org. JDOM. XPath .*; Import org. JDOM. Input .*; Import java. Io .*; Import java. util .*; Public class test { Public static void main (string [] ARGs) throws exception { Saxbuilder builder = new saxbuilder (); Document Doc = builder. Build ("KK. xml "); Element root = Doc. getrootelement (); XPath = XPath. newinstance ("// phone number [../name = 'zhang san'] [@ type = 'home']"); List list = XPath. selectnodes (Root ); Iterator iter = List. iterator (); While (ITER. hasnext ()){ Element item = (element) ITER. Next (); System. Err. println (item. gettext ()); } } The output result is exactly what we want: (010) 88888888. How about it, very convenient :). After 8, my expression is not necessarily the most efficient. You have better understanding of xpath and better query efficiency. Hope this little articleArticleI am inspired by you. If you have any mistakes, please criticize and correct them.
Copyright Notice to the author |
Does this article help you? Vote: Yes NoVoting Result: 6 1
|
|
|
|