Reproduced Jdom/xpath Programming Guide

Source: Internet
Author: User
Tags processing instruction xml parser xquery

Jdom/xpath Programming Guide

This article describes the benefits of JDOM and XPATH, and the combination of both for XML programming.

Objective

XML is a good form of data packaging and data exchange, in today's XML big line in the world, if not heard of its name, it is really ignorant. The advantages of using XML to describe data are obvious, it has the dual effect of simple structure, convenient for human and machine reading, and makes up the insufficiency of relational data to the real data description ability in the objective world. According to the needs of the technical field, the organization developed the format specification of XML, and set up a descriptive model, referred to as DOM. Various popular programming languages have launched their own XML parser according to this model, and in the Java World, the Xerces developed by Apache should be one of the most popular and powerful XML parsers. However, since the design of the DOM model is not designed for a particular language, so in order to be universal, adding a lot of cumbersome and unnecessary details, so that Java programmers in the development of XML application process is not very convenient, so jdom as a new kind of XML parser turned out, It does not follow the DOM model and builds its own independent set of jdom models (note that Jdom is never a DOM extension, although the names are similar, but both are parallel) and provide a powerful, easy-to-use class library that enables Java programmers to develop their own XML applications more efficiently. and greatly reduced the amount of code, so it quickly gained recognition in the industry, such as JBuilder, such as the aircraft carrier-grade heavyweight products are jdom as an XML parsing engine, it is well-deserved.

With the specification of XML data, it is natural to think that there should be a query language that can find the data of any node in the XML, just as the SQL statement can execute the query operation in the relational database, so XQuery and XPath conform to the trend. Since XQuery is more complex, inconvenient to use, XPath is becoming mainstream, we only need to learn from XPath to cope with all the query requirements. In the latest version of V1.0BATA10 released by Jdom, support for XPath has been added, which is undoubtedly exciting for developers.

Learn Jdom and XPath, you are no longer the beginning of XML, in the future of development career, like the special forces of the multi-dagger, for you to help you go forward. Gossip, learning to be down-to-earth, from the beginning.

XPath Express article

XPath follows the path format of the Document Object Model (DOM), since each XML document can be viewed as a tree with many nodes, each of which can be one of the following seven types: root (root), element, attribute (attribute), body (text), Namespaces (namespace), processing instructions (processing instruction), and annotations (comment). The basic syntax for XPath consists of an expression. An object is generated after the value of the expression is evaluated, which has the following four basic types: Node-collection, Boolean, numeric, and string. XPath is basically similar to finding files in the file system, and if the path begins with a "/", it indicates that the path represents an absolute path, which is consistent with the definition of the file path in the UNIX system. Starting with "//" means finding it anywhere in the document.

Without talking about general theories, learning XPath is the quickest and most efficient to learn from examples and helps you extrapolate.

The following sample XML document describes the basic information about a hard disk in a computer (root node <HD> represent hard disk,<disk> label represents hard disk partition, from its Name property can be seen there are two drive letter names "C" and "D" partition; each partition contains < Capacity>,<directories><files> three nodes, respectively, representing the size of the partition, the number of directories, the number of files included):

<?xml version= "1.0" encoding= "UTF-8"?>

You use positional path expressions in an XML document to find information, and there are many ways to make these expressions.

The search for node elements is the most frequent way you will find them. In the XML document example above, root HD contains disk nodes. You can use paths to find these nodes, separate the nodes with a forward slash (/), and return all elements that match the pattern. The following XPath statement returns all the disk elements:

/hd/disk

"*" means "all". /hd/* stands for all nodes under HD.

The following XPath returns all nodes with the name disk under any node:

Disk

The following XPath will return all nodes with the name Disk,name attribute ' C ':

/hd/disk[@name = ' C ')

The additional elements of the node, such as attributes, functions, etc., are expanded with square brackets, and the property is preceded by the @ sign.

The following XPath returns the files node with a file count of 1580:

/hd/disk/files[text () = ' 1580 ']

It is noted that the above contains a text (), which is a function of XPath, its function is to take out the text of the current node.

The following XPath returns a partition with a file number of 1580:

/hd/disk/files[text () = ' 1580 ']/parent::*

The last Parent::* represents the collection of all the parent nodes of this element.

Some useful functions in XPath:

stringconcat(String, String, string*) joins two strings
boolean starts-with (String, String) Determine if a string starts with another string
Boolean contains (String, string
string substring (string, number, number) substring
number Strong>string-length (String)
Number sum (node-set) sum
Number Floor (number)
numbers ceiling (number) ask for greater than this minimum integer value

XPath has a rich expression function, above these are already basic enough, in your project will find that according to the actual situation there are many query requirements, you should refer to the last offer of this article on the xaph of the official information on the review, I only play a role here, in the following chapters, Our application paradigm will not exceed those mentioned above, and if you are interested in XPath, you should look for relevant materials and books for further study after reading this article.

Jdom cultivation of the article

Programmers who have used xerces will feel that sometimes a word can be said clearly, when using the Xerces API to achieve, to three or four lines of the program.

Get and install Jdom

At http://www.jdom.org/You can download the latest version of Jdom and add all the jar packages in the Jdom.jar and LIB directories in the package to classpath.

Parsing XML with Jdom

All classes of the Jdom model are in org.jdom.* this package, org.jdom.input.* This package contains the Jdom parser, wherein the Dombuilder function is to parse the DOM model document into the JDOM model document The function of Saxbuilder is to parse an XML tree that conforms to the Jdom model from a file or stream. Since the XML sample we mentioned above is stored in a file called Sample.xml, it is clear that we should use the latter as the parsing tool. The following program demonstrates the basic function of jdom, which is to parse an XML document and pick some content to output to the screen.

Import Java.util.*;import Org.jdom.*;import Org.jdom.input.saxbuilder;public class Sample1 {public static void main ( String[] args) throws exception{   Saxbuilder sb=new saxbuilder ();  Document doc=sb.build ("Sample.xml");  Element root=doc.getrootelement ();  List List=root.getchildren ("Disk");  for (int i=0;i<list.size (); i++) {   element element= (Element) list.get (i);   String name=element.getattributevalue ("name");   String Capacity=element.getchildtext ("Capacity");   String directories=element.getchildtext ("directories");   String Files=element.getchildtext ("files");   SYSTEM.OUT.PRINTLN ("Disk information:");   SYSTEM.OUT.PRINTLN ("Partition Drive letter:" +name);   SYSTEM.OUT.PRINTLN ("Partition Capacity:" +capacity);   System.out.println ("Number of directories:" +directories);   System.out.println ("Number of files:" +files);   System.out.println ("-----------------------------------");}}   

The output of the program:

Disk information: partition drive: C partition Capacity: 8G Number of directories: 200 files: 1580-----------------------------------disk information: partition drive: D partition capacity: 10G Number of files: 500 file:-------- ---------------------------

This procedure uses the traditional analytic method, the first level from the root node to the child node one by one collects the data which we need, is very. Imagine if this tree is deep enough, we want to take the third node of the 5th 0 layer data (exaggerated point, hehe), it will be a nightmare! The following content will easily dissolve your pain.

Jdom+xpath Advanced Article

Having said so many jdom and XPath benefits, it's time for heroes to come into play.

Jdom's XPath API is org.jdom.xpath in this package. Look at this package, there is only one class, Jdom is so concise, nothing is so complicated. The core APIs in this class are mainly two selectnodes () and selectSingleNode (). The former returns a set of nodes based on an XPath statement, which returns the first node that meets the criteria based on an XPath statement.

The following program we use Jdom+xpath to achieve the same function of the previous program, you can learn a lot of the use of XPath knowledge:

Import Java.util.*;import org.jdom.*;import Org.jdom.input.saxbuilder;import Org.jdom.xpath.xpath;public class  Sample2 {public static void main (string[] args) throws Exception {Saxbuilder sb = new Saxbuilder ();  Document doc = Sb.build ("Sample.xml");  Element root = Doc.getrootelement ();  List List = Xpath.selectnodes (Root, "/hd/disk");   for (int i = 0; i < list.size (); i++) {Element disk_element = (Element) list.get (i);   String name = Disk_element.getattributevalue ("name"); String capacity = ((Text) Xpath.selectsinglenode (disk_element, "//disk[@name = '" + name + "']/capacity/text ()")). Gette   Xtnormalize (); String directories = ((Text) Xpath.selectsinglenode (disk_element, "//disk[@name = '" + name + "']/directories/text ()")   ). Gettextnormalize (); String files = ((Text) Xpath.selectsinglenode (disk_element, "//disk[@name = '" + name + "']/files/text ()")). Gettextnor   Malize ();   SYSTEM.OUT.PRINTLN ("Disk information:");   SYSTEM.OUT.PRINTLN ("Partition drive letter:" + name); System.out.printlN ("Partition capacity:" + capacity);   System.out.println ("Number of directories:" + directories);   System.out.println ("Number of files:" + files);  System.out.println ("-----------------------------------"); } }}

Output Result:

Disk information: partition drive: C partition Capacity: 8G Number of directories: 200 files: 1580-----------------------------------disk information: partition drive: D partition capacity: 10G Number of files: 500 file:-------- ---------------------------
Conclusion

Technology in the ever-changing development. Never after learning, you can once and for all technology. The development of XML rapid. As the authoritative organization of Internet, the Internet has been guiding the development direction of web technology. The emergence of new technology is mostly around the standard established by the People's Congress, but often some "heterodoxy" alternative work method can produce amazing lethality. Jdom is a wonderful flower in many pang men. Like the big line of Java EE today, there are many open-source organizations still silently build their own exclusive weapons, who can say in the near future, they will not become epoch-making creation? The rise of hibernate is powerfully shaking the cornerstone of the EJB architecture in Java EE. As long as the frame is formed, there must be a weak soft rib. As long as the new technology can penetrate each other's weaknesses, they can stand in the industry. This article only plays a role, I believe the reader after eating this fast food, will be sure to find a more beautiful scenery outside the window waiting for us to travel.

Reprinted from: https://www.ibm.com/developerworks/cn/xml/x-jdom/

Resources
    • For an authoritative document on XPath published by the publisher, visit http://www.w3.org/TR/2002/WD-DOM-Level-3-XPath-20020328
    • Jdom official website can download the latest Jdom class library http://www.jdom.org

Reproduced Jdom/xpath Programming Guide

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.