JDOMXPATH Programming Guide

zhaozj2021-02-16  105

content:

Foreword XPath Quick Articles JDM repair articles to get and install JDOM parsing XMLJDOM XPath Advanced Reference Reference About the author

In the XML area:

Teaching tools and products all articles

Xue Gu Yu (Rainight@126.com) Nordsan Information Technology Development Co., Ltd. Advanced Java Engineer May 2004

Preface XML is an excellent data package and data exchange form. In today's XML, the big row is in the world. If you have not heard of its big name, it is really lonely. The advantages of describing data with XML are obvious, it has a simple structure, facilitating the double effect of human and machine reading, and compensates for the deficiencies of relational data on real data descriptions in the objective world. The W3C organization developed XML format specification according to the needs of the technical field, and established a description model, referred to as DOM. Various popular programming languages ​​have launched their own XML parsers based on this model. In the Java world, Xerces developed by Apache organizations should be one of the most powerful XML parsers. However, since the W3C is designed to design the DOM model, it is not designed for a language. Therefore, for versatility, there are many cumbersome and unnecessary details, so that Java programmers are not very convenient in developing XML applications. Therefore, JDOM is born as a new XML parser. It does not follow the DOM model and established its own independent JDOM model (note that Jdom is never dominant, although the name is almost, but the two is parallelism) And provide a powerful class library that makes the Java programmers to develop their XML applications more efficiently, and greatly reduce the amount of code, so it quickly got the industry's recognition, such as jbuilder like this. The aircraft carrier-level heavy product is an XML parsing engine with JDOM, and it is not intriguing. With the description of XML data, people will naturally think that there should be a query language to find data on any node in XML, just like the SQL statement can perform query operations in relational database, so XQuery and XPath adapt to the trend, Shun it. Since XQuery is more complicated, it is not easy to use, XPath gradually became mainstream, we only need to learn XPath, you can cope with all query requirements. In the latest V1.0bata10 version released by JDOM, support for XPath has been joined, which is undoubtedly a very excited developer. Learn JDOM and XPath, you are no longer the entry of XML, in the future development career, like a special soldier's more dagger, for you, to make you go forward. Leisure less, learn to work hard, start from the beginning. XPath Quick Article XPath Follow the Document Object Model (DOM) path format, because each XML document can be seen as a tree with many nodes, each node can be one of the following seven types: root (root ), Element, attribute, a name space, process instruction, and comment. The basic syntax of XPath is composed of expressions. An object is generated after calculating the value of an expression, which has the following four basic types: node collection, Boolean, digital, and string. XPath is basically similar to the file system, if the path is starting with "/", it indicates that the path represents an absolute path, which is consistent with the definition of the file path in the UNIX system. The beginning of "//" is indicated in any location in the document. Don't talk about the general theory, learn XPath, you have to learn from an instance, and help you give an Anti-three.

The following sample XML document describes the basic information of a hard drive in a computer (root node represents the hard disk, the label represents the hard disk partition, from its Name property, there is two disk names " C "and" D "partition; each partition contains , , representing the space size, number of directories, number of files included in the partition):

8G

200

1580

10g

500

3000

You use location path expressions in the XML document to find information, which have many ways to make a way. Finding node elements is the most frequent lookup of you will encounter. In this XML document example, the root HD contains a DISK node. You can use the path to find these nodes, use the positive slash (/) to separate the nodes, return all elements that match the pattern. The following XPath statement returns all DISK elements: / hd / disk "*" means "all" mean. / Hd / * represents all nodes under the HD. The following XPath will return all nodes of any node as DISK: // Disk The XPath below will return all nodes named DISK, name attribute is 'c': / hd / disk [@ name = 'c']] Additional elements of nodes, such as attributes, functions, etc. must be extended by square brackets. In front of the property, add the XPath below @ 号 will return files nodes for the number of 1580: / hd / disk / files [text () = '1580'] Everyone notes above containing a text (), which is a function of XPath, which is the text of the current node. The following XPath will return a partition of the file number of 1580: / hd / disk / files [text () = '1580'] / parent :: * Last Parent :: * Represents all the collections of all parent nodes of this element. Some useful functions in XPath:

String Concat (String, String, String *) Joints Two Strings Boolean Starts-with (String, String) Determines whether a string begins with another string Boolean Contains (String, String) to determine if a string contains another String SUBSTRING (STRING, NUMBER, NUMBER) Subtrings Number String-length (String) String Length Number SUM (Node-Set) Q & NUMBER FLOR (NUMBER) is smaller than the maximum integer value Number CEILING (NUMBER) Significantly greater than this minimum integer XPath has a rich expression function, which is basically enough. If you do a project, you will find that there are many query requirements according to the actual situation, you should refer to the W3C released by this article. Regarding the official information of XAPH, I only give it a role of pouring jade here. In the following chapters, our application example will not exceed these content mentioned above. If you are interested in XPath, you should read this article. Look, find relevant information and books in-depth study. JDM cultivation articles will feel, sometimes it can be clear, and when using a sentence, when you implement the API of XERCES, you need to three or four lines. Get and install JDOM at http://www.jdom.org/ can download the latest version of JDOM, add all JAR packets in the jwan package in the compressed package to ClassPath. All classes of the XML JDOM model with JDOM are in org.jdom. * This package, org.jdom.input. * This package contains JDOM's parser, where DomBuilder's function is to analyze the DOM model The Document; Saxbuilder's functionality of the Jdom model is to resolve the XML tree that conforms to the JDOM model from the file or stream. Since our above mentioned XML sample stores in a file named Sample.xml, it is clear that we should adopt the latter as a parsing tool. The following program demonstrates the basic function of JDOM, which is analyzes an XML document and selects some content to output it on 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

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 Distribution:" Name);

System.out.println ("Partition Capacity:" Capacity);

System.out.println ("directory:" Directories);

System.out.println ("Number of Files: Files);

System.out.println ("-------------------------------");

}

}

}

The output of the program:

Disk information:

Partition disk character: c

Partitioning capacity: 8G

Number of directors: 200

Number of documents: 1580

-----------------------------------

Disk information:

Partition disk man: D

Partitioning capacity: 10g

Count: 500

Number of documents: 3000

-----------------------------------

This program uses traditional parsing, and the primary level of the primary level to the child node one by one of the data we need, the mid-rulement. Imagine if this tree is deep enough, we want to take the data of the third node of the 5th floor (exaggerated, huh, huh), that will be a nightmare! The following content will easily resolve your suffering. JDOM XPath advanced the story of so many JDOM and XPath, finally arrived at the hero of Wu Zhi, Jdom of the API of XPath is in the org.jdom.xpath. Take a look at this package, only one class, Jdom is so simple, what is not so complicated. The core API in this class is primarily two SelectNodes () and selectsinglenode (). The former returns a set of nodes according to an XPath statement; the latter returns the first node in accordance with an XPath statement. The following programs we implemented the same functionality in the previous program with JDOM XPath, you can learn a lot of XPath knowledge from middle school:

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 ")")). GetTextNormalize ();

String Directories = (text) xpath.selectsinglenode (Disk_element, "// disk [@ name = '" name ")'] / Directories / text ()")). GetTextNormalize ();

String files = ((text) xpath.selectsinglenode (Disk_element,

"// disk [@ Name = '" Name "))). getTextNormalize ();

System.out.println ("Disk Information:");

System.out.println ("Partition Distribution:" Name);

System.out.println ("Partition Capacity:" Capacity);

System.out.println ("directory:" Directories);

System.out.println ("Number of Files: Files);

System.out.println ("-------------------------------");

}

}

}

Output results:

Disk information:

Partition disk character: c

Partitioning capacity: 8G

Number of directors: 200

Number of documents: 1580

-----------------------------------

Disk information:

Partition disk man: D

Partitioning capacity: 10g

Count: 500

Number of documents: 3000

-----------------------------------

The conclusion technology is developing in the same day. Once you haven't learned, you can once again. The development of XML has a thousand miles away. The W3C as an authoritative organization of Internet guided the development direction of Internet technology. The emergence of new technologies surrounded W3C, but there are often some kinds of "left-door" alternative to produce amazing killing. Jdom is a wonderful flower in this many side doors. Just like J2EE, today, there are many open source organizations that are still silently to create their own exclusive weapons. Who can say that in the near future, they will not become the creation of the epoch? I don't see Hibernate's rise is powerful. The cornerstone of the EJB architecture in J2EE. As long as it is a forming frame, there must be weak weakness. The new technology can sit in the industry as long as it can attack the other party's weakness. This article only plays the role of throwing bricks, I believe that after eating this fast food, I will definitely find that there is a more beautiful scenery outside the window to travel. Reference

W3C released about XPath's authority documentation, please 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. jday.org

About author

Xue Guyu is Nordsan (Beijing) Information Technology Development Co., Ltd. Is committed to the development of server products for enterprise-level heterogeneous data exchange. It has a relatively rich development experience in J2EE and Web Service, you can pass Rainight @ 126.com got contact with him.

转载请注明原文地址:https://www.9cbs.com/read-10432.html

New Post(0)