China | Hotline: 800-810-3786 How to Buy | My Sun | Home >> User Original Articles Using JXPath Access Java Objects, Collection and XML Files
Author: Xiao Jing
About the Author
J2DEE, Web Services and their implementation on WebSphere, WebLogic platforms, with IBM developing with WebSphere Studio certificates. You can get in touch with GuiLaida@163.com and the author, or view the author's home page for more information.
Summary
JXPath is an XPath implementation provided by the Apache organization. With jxpath, you can use XPath syntax, function to access different data content, including Java objects, collection, XML content, various objects in the web application environment, this article is simple The JXPath and demonstrated how to access the Java object, the collection, and XML files through the class library provided by JXPath, and give a simple comment.
I. Introduction to JXPath is a Java implementation provided by Apache, part of Jakarta, the latest version is 1.1, JXPath's main feature is a set of Java Class libraries to use XPath to access JavaBeans specification, Java Collection, other objects with dynamic properties (such as MAP, ServletContext, etc.), while providing a set of extended mechanisms to enable us to add support for other object models other than these objects.
[Note] 1. For more content about XPath, please visit the homepage of XPath http://www.w3schools.com/xpath/default.asp 2, more content about jxpath, please visit the homepage of JXPath http: // Jakarta.apache.org/commons/jxpath/index.html 2, Environment Preparation 1 -jxpath-1.1.zip
2. Download the Eclipse author used Eclipse as a development tool, please download the latest version of Eclipse to www.eclipse.org.
3, download the Tomcat Author uses Tomcat as a web container to demonstrate how to use JXPath to access the object in ServletContext, please go to jakarta.apache.org to download the latest version of Tomcat. The following sections will detail how to use JXPath to access a wide variety of objects while demonstrating how to create objects, modify the properties of objects through JXPath.
Third, using the JXPath access object content 3.1 Access JavaBean properties 1, prepare a Java class author that meets the requirements for a COMPANY class, which includes 3 properties: ID, name, and address, code as follows: package org.vivianj.jxPath. Examples.pub;
Import java.util.comParetor; import org.apache.log4j.logger;
public class Company implements Comparator {public static Logger logger = Logger.getLogger (Company.class); private String name = ""; private int id = 0; private String address = ""; public void setName (String p_name) {this. name = p_name;} public void setId (int p_id) {this.id = p_id;} public void setAddress (String p_address) {this.address = p_address;} public String getName () {return this.name;} public int getId () {Return this.id;} public string getaddress () {return this.address;} public int compare (Object O1, Object O2) {Return 0;} public boolean equals (object obj) {boolean result = false; if (Obj InstanceOf Company) {Company Company = (Company) Obj; if (Company.GetId () == this.id && company.getname (). Equals (this.getname ()) && company.getaddress (). Equals ( this.getaddress ()) Result = true;} Return Result;}} 2, using jxpath to access the Java class's property Now we use JXPath to access this class's properties, the test code is as follows: // Instantiate a Company object Company C ompany = new company ();
/ / Set the individual attributes of the object Company.SetId (1); Company.SetName ("Vivianj Organization); Company.SetAddress (" www.vivianj.org ");
// Initialize JXPath's context environment jxpathcontext context = jxpathcontext.newcontext (Company);
// Use XPath syntax to access the object's properties // getValue method "name", "ID", "address" use XPath's syntax, // they represent the property name, ID, addressString, which is to access the company object, Id, AddressString Name = (String) Context.getValue ("name"); Integer ID = (Integer) Context.getValue ("ID"); string address = (string) Context.getValue ("Address");
3.1.1 Lenient Access Mode This is likely to appear in the above access method: If the properties you want to access are not the properties of this Java class, the system will report a violation during the execution - org.apache.commons .jxpath.jxPatHexception: no value for xpath: xxx (xxx is the name of the property you want to access). This situation is harmful to the stability of the program, and the robustness is harmful. At this time, we should use the Lenient access mode provided by JXPath to avoid this situation, in Lenient Access mode, if you visit the non-existing properties, the system will Returns a NULL instead of throwing a violation.
To use the Lenient access mode, it is easy to add context.setlenient (TRUE) in the code, the specific operation is as follows:
// Instantiate a Company ID Company COMPANY = New Company ();
/ / Set the individual attributes of the object Company.SetId (1); Company.SetName ("Vivianj Organization); Company.SetAddress (" www.vivianj.org ");
// Initialize JXPath's context environment jxpathcontext context = jxpathcontext.newcontext (Company);
// Notify the system Use the Lenient Access Mode Context.setlenient (TRUE)
// Use XPath syntax to access the properties of the object String Name = (String) Context.getValue ("Name1");
[Note] Name1 is not an attribute of the Company class, but since the Lenient access mode is used, the system returns NULL.
3.2 Access to the Embedded Properties 3.1 Demos how to access the simple type properties of the class, if the properties of the class are a class type, what is the situation, the following example will demonstrate this way of access:
1. Prepare the Association class Association class has a property companies, he itself is a COMPANY class type package org.vivianj.jxpath.examples.pub;
Import java.util.Arraylist; import java.util.collection;
Public class association {private company getcompany;} public void setcompany;}}} = p_company;}}
2, access the nested property // instantiate the association class association association = new assistation ();
// Instantiate Company Class Company Company = New Company (); Company.SetId (1); Company.setName ("Vivianj Organization); Company.SetAddress (" www.vivianj.org ");
// Set the Company property association.setcompany (Company) for Association objects; COMPANY
// Initialization JXPATH context = jxpathcontext.newcontext (association);
// Use the Lenient Access Mode Access Nested Attribute Context.setlenient (TRUE);
/ / Get the value of the specified attribute to get the value of the specified attribute // in which the parameter "company / name" of the getValue method "Company / Name" // of the Part "represents the property company, // second part (" / "The part of the symbol) Name Representative Is the properties of the Company String name = (String) Context.getValue ("Company / Name"); 3.3 Access Java Collection JXPath can access the Java collection content, including Java arrays, Collection classes, and their subclasses, their access The way is basically similar, please refer to the program code below for details:
1. Extend the Association class, add a method of providing an array of Company objects to the Association class GetCompanySinArray method, the signature and content of the method are as follows: public company [] getcompanysinaray () {for (int i = 0; i <5; i ) {// Instantian new Company object companies company commit = new company (); Comp.setId (i); Comp.setName ("Name" i); Comp.SetAddress ("Address i); // Assign the instantiated object assignments to the corresponding elements of the array companiesinArray [i] = comp;} return companysinarray;
2, extend the association class, add a collection of collation to the COMPANY object to add a method for the Association class, the method, the method's signature and the contents are as follows: public collection getcompanysincollection () {for (int i = 0; i <5; i ) {/ / Instantian New Company Object Company Comp = New Company (); Comp.SetId (i); Comp.setName ("Name" i); Comp.SetAddress ("Address" i); // Put instance The object is added to groupsincollection.add (comp);} returncysincollection;}
3.3.1 Accessing Method The detailed code of the JXPath access array is as follows:
// instantiate the association class association association = new association ();
// Initialization JXPATH context = jxpathcontext.newcontext (association);
// Use the Lenient Access Mode Access Nested Attribute Context.setlenient (TRUE);
/ / The Name Properties of the Name Properties // GetValue Method of the recorded Name Properties // of the COMPANYSINARRAY [5] / Name "by the JXPath grammatical access to the number of the" CompanySinarray [5] / Name "are association properties, // 5 represents the 5th representative Elements, name representative name String Name = ("CompanysinArray [5] / Name";
// By XPath syntax access Name attribute // getValue's parameter "CompanySincolletion [5] / Name" in the COMPANYSINCOLLETIONCOLLETION is the property name of Association, // 5 represents the 5th representative access collection Element, name represents the attribute name of the fifth element String name = ("" "" COMPANYSINCOLLETY [5] / Name "); [Note] XPath access arrays or sets, array or collections are from 1 Start, this point is a bit different from 0 from 0 specified in the Java language.
3.3.2 Get a number of records Since it is access to collection data, such a need often appears: a number of records that meet the requirements are needed. This situation is also very convenient to use JXPath. You can use the corresponding xPath information using the corresponding XPath information. The content returned after the operation is saved in the Iterator object. It can be accessed. The specific code is as follows:
1. Get // instantiate the association class association association = new association () by the location where the record is located.
// Instantiate the jxpath context jxpathcontext context = jxpathcontext.newcontext (association);
/ / Get all records of all records in the array to 3 // iTerator method, the parameter of the ipanaRray [Position ()> 3] Using XPath's syntax // in which CompanySinArray is the properties of the Association object, he is an array // position ( ) Is the built-in function in XPath, get the subscript itarator companySinarray = context.iterate ("CompanySinArray"); "CompanySinArray");
/ / Get all records of all records in the collection // iTerator method for all records of the item (Position ()> 3] Use the syntax of XPath // wherein the companySincollection is an attribute of the Association object // he is a collection type or Is an instance of its subtype // position () is the built-in function in XPath, gets the location of the record in the collection = context.iterate ("CompanysIncollection [posient ()> 3]");
2. Get // instantiate the association class association association = new association () by specified rules.
// Instantiate the jxpath context jxpathcontext context = jxpathcontext.newcontext (association);
// Get the Name property of the object in the array for the parameters of all objects // iTerator method of the 'Name3', the parameters of the Iterator method, using XPath's syntax // where CompanySinArray is the properties of the Association object, he is an array // name = 'name3' is a conditional expression, indicating that the Name attribute value of the return object must be Name3ITARATOR COMPANYSINARRAY = Context.Item ("CompanysinArray [name = 'name3');
// Get the Name property of the object's Name property of 'name2' All objects // iTerator method's parameters of the parameter method [name = 'name3'] Using XPath's syntax // in which CompanySincollection is the properties of the Association object // he is a A Collection type or an instance of its subtype // name = 'name3' is conditional expression, indicating that the Name attribute value of the return object must be Name3ITARATOR COMPANYSINCOLLECTION = context.Ist ("CompanySincollection [name = 'Name3'); 3.4 Content accessing the MAP object 1, prepare the eligible Java class package org.vivianj.jxpath.examples.pub;
Import java.util.hashmap; import java.util.map;
Import org.apache.commons.jxpath.jxpathContext;
Public class mymapsource {private map map = new hashmap (); public mymapsource () {map.put ("ID", new integer (5)); map.put ("name", "name");} public map getMapSource () {Return this.map;}}
2, to access the contents of Map using JXPath // instantiate objects MyMapSource MyMapSource myMapSource = new MyMapSource (); // instantiate JXPath context JXPathContext context = JXPathContext.newContext (myMapSource); // Map object to access the content through the getValue // JXPath The method's parameters use the maporce in the XPath syntax // mapSource / ID represent the properties of the MyMapSource object, and he is an object of the MAP type, ID represents the ID field of the Map object Integer ID = (Integer) CONTEXT.GETVALUE "MapSource / ID");
3.5 Access XML file 1, write your own XML file XML Version = "1.0"?>
2. Write a class, return to the eligible Company content package org.vivianj.jxpath.examples.pub;
Import java.net.URL;
Import org.apache.commons.jxpath.container; import org.apache.commons.jxpath.xml.documentContainer; public class companys {private container companys = null;
Public container getcompanys () {if (companys == null) {// Get the content URL URL URL = getClass (). getresource ("companys.xml"); // Bind XML content into CompanyS object companies = New DocumentContainer (URL);} Return CompanyS;}}
3. Use JXPath to access the contents of the XML file // instantiate CompanyS object companies companys = new companys ();
// Initialization JXPATH context jxpathcontext context = jxpathcontext.newcontext (company);
/ / Get the content of the child element of the specified record / * GetValue method "CompanyS / companyS / Company [@ID = '101'] / address / street" uses the first companyS in the XPath syntax to represent access to the companyS object The COMPANYS Property The second companyS indicates that the companies in XML data companies, address, and street are the name @ID = '101' is a conditional expression in XML. 101 * / string street = (string) Context.getValue ("CompanyS / CompanyS / Company [@ID = '101'] / address / street");
/ / Get the value of the attribute of the XML element through jxpath ("ID =" context.getValue ("CompanyS / companyS / company [@ID = '101'] / @ ID")))
// Get the value of the sub-elements of the XML element via jxpath ("p_id =" context.getValue ("Companys / Companys / Company"));
[Note] When accessing XML content via jxpath, if the access attribute, an @ symbol must be added to the distinction
Fourth, summary JXPath is a Java implementation provided by the Apache organization. The latest version is 1.1, through the rich class library provided by JXPath, users can use XPath syntax to access Java objects, collections, XML content, Various objects, etc. in the web application environment.
In this paper, the author starts with simple introduction of JXPath related information. In the next chapter, the author combines examples, detailed demonstrates how to access Java objects, collections, and XML files through the rich class library provided by JXPath, at the same time Give a simple comment, I hope to help you enter the wonderful world of JXPath. JXPath's powerful features are far more than this, please pay attention to the authors of the author.
Tool Download 1, JXPath Package Http://apache.linuxForum.Net/dist/jakarta/commons/jxpath/binaries/commons-jxpath/binaries/commons-jxpath-1.1.zip2, Assile Tool Download WWW.ECLIPSE.ORG References 1, JXPath User Guide http://jakarta.apache.org/commons/jxpath/index.html
2, XPath syntax http://www.w3schools.com/xpath/default.asp technology forum >> Java Forum >> Solaris Forum >> Sun Java Enterprise System Forum Training Center >> Self-test >> Technical Training Services> > Technical Certification Program Technology >> Java Topics >> Solaris Topics >> Sun Java Enterprise System Topics Resource Center >> References >> Shared Code >> Successful Case >> White Paper >> Common Q & A >> Download Center >> Product Introduction >> Programming skills
-------------------------------------------------- ------------------------------ About Sun | Contact Us | Terms of Use | Privacy Policy | CopyRight 1994-2004 Sun Microsystems