Add XPath to JavaBeans

Source: Internet
Author: User

 


Request addressbook [1] to a JavaBean. state. code is a common way to interact with ans, but you can use more powerful XPath specifications.

The purpose of creating XPath is to access and modify XML data. However, a new project of Apache Jakarta allows you to apply powerful XPath specifications to normal JavaBeans.

As an example, we use a JavaBean with the following structure:

Person. name is a String
Person. age is an integer.
Person. birthtown is a Town object
Person. address is an array of Address objects.
Town. name is a string
Address. number is a string
Address. street is a string
Address. town is a Town object

(For simplicity, no source code is provided)

For a given Person object, you can use "name" to get the object name. You can use "birthtown/name" to get the name of the origin, you can also use "address [number = 21]/town/name" to get the name of the town associated with the address (for example, 21.

Apart from being more powerful, the main difference between XPath and the common bean symbols is that elements are separated by backslash (/) rather than periods (.). Once you get used to this feature, it will become very simple.

The following code demonstrates how easy it is to apply the XPath symbol to our JavaBean structure using JXPath:

Import org. apache. commons. jxpath. JXPathContext;
....
Person person = ....;
JXPathContext context = JXPathContext. newContext (person );
System. out. println (context. getValue ("name "));
System. out. println (context. getValue ("age "));
System. out. println (context. getValue ("birthtown/name "));
System. out. println (context. getValue ("address [number = 21]/street "));
System. out. println (context. getValue ("address [number = 21]/town/name "));
....
XPath can be used to set values or create beans. Of course, it can also read values. For more information about XPath and its JXPath implementation, see the JXPath site.

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.