Forward access to java objects, collections and XML files using JXPath

Abstract

JXPath is an XPath implementation provided by the Apache organization. Through JXPath, you can use XPath syntax and functions to access different data content, including java objects, collections, xml content, various objects in the web application environment, etc. The author of this article Briefly introduce JXPath, and demonstrate the detailed process of how to access java objects, collections and XML files through the class library provided by JXPath, and give simple comments at the same time.

1. Introduction to

JXPath JXPath is the java implementation of XPath provided by apache company. It is a part of jakarta. The latest version is 1.1. The main function of JXPath is a set of java class libraries to use XPath to access java classes, java classes that conform to the JavaBeans specification. Collection (Collections), other objects with dynamic properties (such as Map, ServletContext, etc.), and provides a set of extension mechanisms so that we can add support for other object models than these objects.
[Note] •1. For more information about XPath, please visit the XPath homepage
http://www.w3schools.com/xpath/default.asp
•2. For more information about JXPath, please visit the JXPath homepage
http: //jakarta.apache.org/commons/jxpath/index.html

2. Environment preparation
1. Download JXPath
The latest version of JXPath binary code download address is
http://apache.linuxforum.net/dist/jakarta/commons/jxpath /binaries/commons-jxpath-1.1.zip


• 2. Download eclipse
The author uses eclipse as a development tool, please go to www.eclipse.org to download the latest version of eclipse.


• 3. Download Tomcat
The author uses Tomcat as a Web container to demonstrate how to use JXPath to access objects in ServletContext. Please download the latest version of Tomcat from jakarta.apache.org.

The following chapters will demonstrate in detail how to use JXPath to access various objects, and will demonstrate how to create objects, modify object properties and other functions through JXPath.

3. Use JXPath to access object content

3.1 Access JavaBean properties
1. Prepare a Java class that meets the requirements The
author made a Company class, which includes 3 properties: ID, Name and Address, the code is as follows: package org.vivianj.jxpath .examples.pub;

import java.util.Comparator;
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. Use JXPath to access the properties of the java class
Now we use JXPath to access the properties of this class, the test code is as follows: //Instantiate a Company object
Company company = new Company ();

//Set each property of the object
company.setId(1);
company.setName("vivianj organization");
company.setAddress("www.vivianj.org");

//Initialize the context of JXPath
JXPathContext context = JXPathContext.newContext(company);

//Use XPath syntax to access the properties of the object
//The parameters "name", "id", and "address" of the getValue method use XPath syntax,
//they represent the attributes name, id, and address of the company object to be accessed
String name = (String)context.getValue(" name");
Integer id = (Integer) context.getValue("id");
String address = (String)context.getValue("address");



3.1.1 Lenient access mode

In the above access mode, there may be In this case: If the property you want to access is not a property of this Java class, then the system will report an exception during the execution process -- org.apache.commons.jxpath.JXPathException: No value for xpath: xxx (xxx is what you want the name of the property being accessed).

This situation is harmful to the stability and robustness of the program. At this time, we should use the Lenient access mode provided by JXPath to avoid such a situation. In the Lenient access mode, if you access a property that does not exist, the system will Returns a null instead of throwing an exception.

To use the Lenient access mode is very simple, just add a context.setLenient(true) call to the code, the specific operation is as follows:
//Instantiate a Company object
Company company = new Company();



company.setName("vivianj organization");
company.setAddress("www.vivianj.org");

//Initialize the JXPath context
JXPathContext context = JXPathContext.newContext(company);

//Notify the system to 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 a property of the Company class, but because the Lenient access mode is used, the system return null.

3.2 Accessing nested properties

The example in 3.1 demonstrates how to access a simple type property of a class. What if the class property itself is a class type. The following example will demonstrate this access method:
1. Prepare an Association The class
Association class has an attribute company, which itself is the company class type package org.vivianj.jxpath.examples.pub;

import java.util.ArrayList;
import java.util.Collection;

public class Association {
private Company company;

public Company getCompany(){
return this.company;
}
public void setCompany(Company p_company){
this.company = p_company;
}

}


• 2. Access nested properties with JXPath // Instantiate the Association class
Association association = new Association() ;

//Instantiate the Company class
Company company = new Company();
company.setId(1);
company.setName("vivianj organization");
company.setAddress("www.vivianj.org");

//Set the Association object The company property
association.setCompany(company);

//Initialize the JXPath context
JXPathContext context = JXPathContext.newContext(association);

//Use the Lenient access mode to access nested properties
context.setLenient(true);

//Get the specified property through the JXPath method the value of
//The parameter "company/name" of the getValue method
//The first part company represents the property company of the Association,
//the second part (the part after the "/" symbol) name represents the property of the company object
String name = (String ) context.getValue("company/name");



3.3 Accessing Java collections

JXPath can access the content of Java collections. These collections include java arrays, Collection classes and their subclasses. Their access methods are basically similar. For details, please refer to the following The program code:
1. Extend the Association class and add a method that provides an array of Company objects Add a method getCompanysInArray
to the Association class, the signature and content of the method are as follows: public Company[] getCompanysInArray(){
  for (int i = 0 ; i < 5 ; i++){
    //Instantiate a new Company object
    Company comp = new Company();
    comp.setId(i);
    comp.setName("Name" + i );
    comp.setAddress("address" + i);
    //Assign the instantiated object to the corresponding element of the array
    companysInArray[i] = comp;
  }

  return companysInArray;
}


• 2. Extend the Association class and add a method that provides a Collection of Company objects Add a method getCompanysInCollection
to the Association class, the signature and content of the method are as follows: public Collection getCompanysInCollection(){
  for (int i = 0 ; i < 5 ; i++){
    //Instantiate a new Company object
    Company comp = new Company();
    comp.setId(i);
    comp.setName("Name" + i );
    comp.setAddress("address" + i) ;
    //Add the instantiated object to the Collection
    companysInCollection.add(comp);
  }

  return companysInCollection;
}



3.3.1 Access method The detailed code for accessing the array

through JXPath is as follows:
//Instantiate the Association class
Association association = new Association( );

//Initialize the JXPath context
JXPathContext context = JXPathContext.newContext(association);

//Use the Lenient access mode to access nested properties
context.setLenient(true);

//Access the name property of the record with an array index of 4 through JXPath syntax
//Parameters of the getValue method" //Part of companysInArray in companysInArray[5]/name"
is the attribute of Association,
//5 means accessing the fifth element in the array, and name means the attribute name of the fifth element
String name = (String) context.getValue(" companysInArray[5]/name");

//Access the name attribute of the fourth record in the collection through XPath syntax //Part of the companysInColletion
in the parameter "companysInColletion[5]/name" of the getValue method
is the attribute name of the Association,
//5 means accessing the fifth element in the collection, name means the attribute name of the fifth element
String name = (String) context.getValue("companysInColletion[5]/name");


[Note] When XPath accesses an array or collection , the subscript of an array or set starts from 1, which is a little different from the 0-start specified in the java language.

3.3.2 Get multiple records

Since it is to access collection data, there is often such a requirement: it is necessary to obtain multiple records that meet the conditions. In this case, it is also very convenient to use JXPath. It is enough to use the iterator method of the context object plus the corresponding XPath information. The content returned after the operation is stored in the Iterator object, which is very convenient to access. The specific code is as follows:
• 1. Get by the location of the record//Instantiate the Association classAssociation
association = new Association();

//Instantiate the JXPath context
JXPathContext context = JXPathContext.newContext(association);

//Get the lower part of the array All records whose marks are greater than 3
//The parameter companysInArray [position() > 3] of the iterator method uses XPath syntax
//where companysInArray is a property of the Association object, which is an array
// position() is a built-in in XPath Function to get the subscript recorded in the array
Iterator companysInArray =
  context.iterate("companysInArray [position() > 3]");

//Get all the records whose position is greater than 3 in the collection
//The parameter companyInCollection of the iterator method [ position() > 3] uses XPath syntax
//where companysInCollection is a property of the Association object
//He is an instance of a Collection type or its subtype
//position() is a built-in function in XPath to get the position recorded in the collection
Itarator companysInCollection =
  context.iterate("companysInCollection [position() > 3] ");


•2. Acquire according to the specified rules//Instantiate the Association classAssociation
association = new Association();

//Instantiate the JXPath context
JXPathContext context = JXPathContext.newContext(association);

//Get the name attribute of the object in the array For all objects of 'name3'
// the parameter companysInArray [name='name3'] of the iterator method uses the XPath syntax
// where companysInArray is an attribute of the Association object, he is an array
//name='name3' is a condition Expression, indicating that the value of the name attribute of the returned object must be name3
Itarator companysInArray =
  context.iterate("companysInArray [name='name3']");

//Get all objects in the collection whose name attribute is 'name2'
//The parameter companysInCollection [name='name3'] of the iterator method uses XPath syntax
//where companysInCollection is a property of the Association object
//he is a Collection type or an instance of its subtype
//name='name3 ' is a conditional expression, indicating that the value of the name attribute of the returned object must be name3
Itarator companysInCollection =
  context.iterate("companysInCollection [name='name3']");



3.4 Accessing the content of the Map object
1. Prepare eligible java classes 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. Use JXPath to access the content of the Map//Instantiate the MyMapSource object
MyMapSource myMapSource = new MyMapSource();
//Instantiate the JXPath context
JXPathContext context = JXPathContext.newContext(myMapSource );
//Access the content of the Map object through JXPath
// The parameters of the getValue method use the XPath syntax
// The mapSource in mapSource/id represents the property of the MyMapSource object,
//He is a Map type object, and the id represents obtaining the Map The id field of the object
Integer id = (Integer) context.getValue("mapSource/id");



3.5 Accessing the XML file
1. Write your own XML file <?xml version="1.0" ?>
    <companys>
      <company id= "101">
      <name>sun</name>
        <address>
          < street>18 #,WenShan Road</street>
        </address>
      </company>

      <company id="102">
      <name>ibm</name>
        <address>
          <street>18 #,WenEr Road</street>
        </address>
      </company>
</companys >


• 2. Write a class that returns the content of the qualified company 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 companies = null;

  public Container getCompanys(){
    if (companys == null){
      //Get the content URL of the XML file
      url = getClass(). getResource("companys.xml");
      //Bind the content of the XML to the companys object
      companys = new DocumentContainer(url);
    }
    return companies;
  }
}


•3. Use JXPath to access the content of the XML file //Instantiate the Companys object
Companys companys = new Companys();

/ /Initialize the JXPath context
JXPathContext context = JXPathContext.newContext(companys);

//Get the content of the child element of the specified record /*The parameter "companys/companys/company[@id = '101']/address/street"
of the getValue method is used XPath syntax where the first companys means accessing the companys attribute of the Companys object The second companys means accessing the companys elements in the XML data company, address, street are the names of elements in xml @id = '101' is a condition Expression, indicating that the id attribute of the qualified company element must be 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
logger.debug("id=" +
  context.getValue("companys/companys/ company[@id = '101']/@id"));

//Get the value of the child element of the xml element through JXPath
logger.debug("p_id=" +
  context.getValue("companys/companys/company[name = 'sun']/name"));



[Note] When accessing xml content through JXPath, if you access attributes, you must add an @ symbol to show the difference

4. Summary

JXPath is a java implementation of XPath provided by apache organization, and the latest The version is 1.1. Through the rich class library provided by JXPath, users can easily use XPath syntax to access java objects, collections, xml content, various objects in the web application environment, etc.

In this article, the author briefly introduces the relevant information of JXPath. In the following chapters, the author combines examples to demonstrate in detail the detailed process of how to access java objects, collections and XML files through the rich class library provided by JXPath. A simple comment is given, hoping to help you enter the wonderful world of JXPath. The powerful functions of JXPath are far more than that, please pay attention to the author's follow-up articles.

Tool download
1. JXPath package download
http://apache.linuxforum.net/dist/jakarta/commons/jxpath/binaries/commons-jxpath-1.1.zip


• 2. Eclipse tools 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

from: http://gceclub.sun.com.cn/yuanchuang/week -13/jxpath.html

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326865565&siteId=291194637