XPath (transfer)

xiaoxiao2021-03-06  62

Usage about XPath

[Author: guoyan1981]

Node match path XPath

The concept of matching is very important during the conversion of XSL. In Template Declaration Statements XSL: Template Match = "" and Template Application Statement XSL: Apply-Templates Select = ", the part of the quotation must be able to accurately locate the node. The specific positioning method is given in XPath.

Alternatively, XPath can be used to search for the XML document.

The concept of introducing XPath is to accurately find a certain node element in order to match the XML document tree. You can use the XPath to be used as a file management path: through the file management path, you can find the required files in accordance with certain rules; the same, according to the rules set by XPath, any of the XML structure document trees can also be found. .

Before introducing the match rules of XPath, let's take some basic concepts about XPath. The first thing to say is the XPath data type. XPath can be divided into four data types:

The Node-SET node set is a collection of a set of nodes that returned by the path match. Other types of data cannot be converted to a node set.

Boolean (Boolean) is matched by the conditional or Boolean expression, which is the same as the Boolean value in the general language, two values ​​of True and FALSE. Boolean values ​​can be converted with numeric types, string types.

String strings that contain a collection of characters, providing a range of string functions in XPath. The string can be converted to the data of the numeric type, the Boolean value type.

NUMBER value is a floating point number in XPath, which can be a double precision 64-bit floating point number. Alternatively, specific descriptions of some values, such as non-numerical nan (not-a-number), infinite infinity, negative infinity -Infinity, positive and negative 0, etc.. Number's integer value can be obtained by a function, in addition, numerical values ​​can be converted to both Boolean types, string types.

The corresponding data types of the three data types and other programming languages ​​are similar, but the first data type is the unique product of the XML document tree. In addition, since XPath is included in a series of operations of the document structure, it is also necessary to understand the XPath node type. Due to the logical structure of the XML document, an XML file can contain logic elements such as elements, cdata, annotations, process instructions, where elements can also contain attributes and can be used to define namespaces. Accordingly, in XPath, the node is divided into seven node types:

Root Node The root node is the top layer of a tree, and the root node is unique. All other elements nodes on the tree are its child nodes or descendants. The processing mechanism for root nodes is the same as other nodes. The matching of the tree in XSLT is always starting from the root node.

Element nodes element node corresponds to each element in the document, the child node of an element node can be an element node, an annotation node, a processing command node, and a text node. A unique identifier ID can be defined for the element node. Element nodes can have an extension, which consists of two parts: part is named space URI, and the other is naming locally.

Text Nodes text nodes contain a set of character data, that is, characters contained in CDATA. No text node has a neighboring brother text node, and the text node has no extension.

Attribute Nodes Each element node has a set of associated property nodes, the element is the parent node of each attribute node, but the property node is not the child node of its parent element. That is to say, by finding the child node of the element, the properties node of the element can be matched, but it is not established, but only one-way. Moreover, the attribute node of the element has no sharing, that is, different element nodes do not share the same attribute node. The processing of defined attributes is equivalent to the defined properties. If an attribute is declared in the DTD, the declaration is #implied, and the property is not defined in the element, the attribute node set of the element does not contain this property. In addition, there is no declaration with the attribute node corresponding to the property. Namespace properties correspond to another type of node. Name Space Node (Namespace Nodes) Each element node has a related namespace node set. In the XML document, the namespace is declared by reserving attributes, so in XPath, the class node is extremely similar to the attribute node, and the relationship between them and the parent element is unidirectional, and does not have sharedness.

Processing Instruction Nodes Processing Instruction Node corresponds to each processing instruction in an XML document. It also has an extension, and the local naming of the extension points to the processing object, and the namespace part is empty.

Comment Nodes comment nodes correspond to the comments in the document. Below, let's construct an XML document tree:

Now, some basic methods that use XPath to match nodes in XML.

The path matching path match is similar to the file path representation, which is better understood. There are several symbols:

Symbolic meaning case matching result / indicator Node path / A / C / D node "a" child node "d" "D", that is, the ID node / root node // all paths of the ID value of D2 Elements // e element ending after "//", the result is the E element for all three E element // c / e all parent nodes C, the result is that the ID value is E1 and E2. Two E-element * paths / A / B / C / * A element → B element → C element under the group B element, the NAME value is b, the D element and ID value of the ID value of D1 is The two E-elements / * / * / * of E1 and E2 have a D element of two-stage nodes. The matching result is a D element of the ID value of D2 // * All elements | Logic or // b | // C B-element and C element position match for each element, each of its sub-elements is orderly. Such as:

Examples Conflict Match Results / A / B / C [1] A element → b / b / c [Last ()] A / B / C [Last ()] a element → The final sub-element ID value of B element → C element is E element E element / A / B / C [position ()> 1] A element → B element → C element is greater than 1 element ID value of 1 D1 D element and two E-element properties and attribute values ​​with ID values ​​can utilize attributes and attribute values ​​to match elements in XPath. It is to be noted that there must be "@" prefix before the element's attribute name. E.g:

Example Configuration Match Result // B [@ID] All B-element ID values ​​with attribute IDs are B1 and B2 // b [@ *] all of the 2 Id properties with id properties B element and a Name property B element // b [NOT (@ *)] all non-attribute B element a elements → B element under C element // b [@ ID = "b1"] ID value is B1 B element B element under a element

The relative relationship matching the XML document can be attributed to the tree structure, so any of the nodes is not isolated. Usually, we will break the property relationship between nodes into a relative relationship, such as father, child, ancestors, offspring, brothers, etc. These concepts can also be used when matching elements. E.g:

Example Configuration Match Results // E / PARENT:: * All E-Node Parent Node Element ID Values ​​are A1 A1 Elements and ID Values ​​C1 C1 // F / AnceStor :: * All F Elements Ancestral Node The group ID value of the element ID value of the element is A1 is a C element of C2 of C2, the b1, b2 B element, the ID value of C2, and there is no attribute. Element / A / Descendant :: * A of all the descendants of the E-element except for all other elements other than the A element // f / self :: * All F element F element itself // f / Ancestor-or-self: * All F elements and its ancestral node elements F elements, F-element parent C elements and A elements / A / C / Descendant-OR-Self :: * All A elements → C elements and their descendants Id value C2 C element, sub-elements B, D, F element / A / c / following-sibling :: * a element → C-element adjacent back sequence All brothers Node elements do not have any attributes / A / C / preceding-sibling :: * A element → C element adjacent front All brothers Node element ID value of B1 and B2 2 B1 and B2 / A / B / C / FOLLOWING:: * a element → B element → c element All element IDs of the sequence are B2 B2, the C element without the attribute, the B element without the attribute, the ID of D2 D2 D element, the F element without attribute, and an E element without the attribute. / A / c / preceding :: * A element → The front of all element IDs of the C element is B2 B2 B2, the ID of E2 E element, the ID is E element E element, the ID of D1 D1, NAME is B B element, ID of C1 C1, b element of ID B1

The conditional matching condition match is the Boolean value of the calculation result of some functions to match the eligible node. Some functions that are commonly used for conditions match have four categories: node functions, string functions, numeric functions, and Boolean functions. For example, Last (), position (), etc. mentioned earlier. These functional functions can help us find the needs of the nodes.

Function and functional action count () function statistics count, return the number of Number () features in the eligible node to convert the text in the value of the value into a value substring () function

Syntax: Substring (Value, Start, Length)

Intercept string SUM () function summary

These features are only part of the XPath syntax, and there are a lot of functional functions that are not introduced, and the syntax of XPath is still growing. Through these functions we can achieve more complex queries and operations.

In these matching methods, the most important path matching is used. Relying on the position of the node to give a subpath relative to the current path. The XQuery ---- The revolutionary data inquiry language (Zeng Yi) in the XML era (Zeng Yi) has quickly received support and concerns from all parties and research institutions since the birth of the documentation and data. Now, many vendors developed using XML to transmit messages (such as SOAP or XML-RPC messages) or as a permanent storage of data (such as XML database). Data query language in the relational database SQL, XQuery will become the mainstream data query language of the XML era. XQuery overview After the popularity of computer networks, the Internet has become one of the important means of obtaining information. With the current chance of technology, people inquiry data on the Internet are also more powerful, and given the query of unstructured data and the relational database Self-defects, people need a more optimized data inquiry language, and XQuery played this role with its good design and powerful features. XQuery is a query language that gets data from an XML format, originated from the XML data query language quilt. And put XPath version 2.0 as its subset. Quilt has a lot of very good features, integrates SQL, ODMG, XPath 1.0, XQL, and XML-QL many features, however, as the amount of information stored in the XML document, for efficient access and Query XML information, Quilt shows its shortcomings. So the new XQuery data query language was born. The XQuery specification launched the Query Language of the W3C in 1998 Boston Semiological Seminar, and the members of the meeting should be divided into two categories. The first category is the person used by the XML as a document, and the second class is the XML as a The person used by data. The invited representative from the industry, academia and research groups uses this opportunity to publish their own views, explain the characteristics and needs of XML query language they think. Query Language Working Group was established after the discussion. This working group is very large, consisting of more than 30 members, XML query language standards represent the needs and views of two types of users. Although XQuery standardized work has been launched in 1998, the time spent in this work is quite long due to differences in XML applications. Until in February 2001, the issuance of the Working Group began to carry out steps, and a large number of documents began to launch. In June and December 2001, an important update was conducted in August 2002 and in May 2003. After joining an XQuery serialization and two full-text related drafts in May 2003, the 12 documents were basically completed, and the draft work is approaching the end. These 12 important documents include: XML Query Requirements (Latest version posted on November 12, 2003) Planning documents for this document Construction team. XQuery demand list. XML Query Use Cases (Latest Version Published on November 12, 2003) This document provides several actual solutions to solve specific problems and the XQuery code snippet. XQuery 1.0: An XML Query Language (Latest Version Published on November 12, 2003) This document is the core document in the draft, introduces the language itself, and an overview of most other content. XQuery 1.0 and XPath 2.0 Data Model (Latest Version Published on November 12, 2003) This document is an extension of the XML information set. Describe the basis of data items and form semantics that the query must be understood.

XQuery 1.0 and XPath 2.0 Formal Semantics (Latest Version Published on November 12, 2003) This document defines the underlying algebra of the language from the form. XML SYNTAX for XQuery 1.0 (Latest Version Published on December 19, 2003) This document is another syntax provided by people who like to use XML. The machines can be used anywhere. XQuery 1.0 and XPath 2.0 Functions and Operators Version 1.0 (Latest Version Published on November 12, 2003) This document describes the basic functions and operators of the Schema data type, the xQuery node, and node sequences. XML Path Language (XPATH) 2.0 (Latest Version Published on November 12, 2003) This document is a separate XPath documentation. XPath Requirements Version 2.0 (Latest Version Published on August 22, 2003) This document is a demand document for XPath. XSLT 2.0 and xquery 1.0 Serialization (Latest Version published on November 12, 2003) This document describes the details of XSLT 2.0 and XQuery 1.0. XML Query and XPath Full-Text Requirements (Latest Version Published on May 2, 2003) This document describes the functional requirements that Full-text Recommendation needs to be achieved. XML Query and XPath Full-Text Use Cases (Latest Version Published on February 14, 2003) This document provides the actual situation that the Full-Text specification is expected to process. XQuery specification work, the latest version of the date of the author is: November 12, 2003, you can get the latest work by the following address http://www.w3.org/tr/xQuery/. XQuery's module structure XQuery module includes three parts: namespace and pattern declaration, function definition, query expressions. The pattern declaration and function definition is not required. (1) The definition of name space is similar to: namespace xs = "http://www.w3.org/2001/xmlschema"(2) The concept of function definition is not unfamiliar with program designers, the following is an example of a function definition (Later we will use this example):

Define Function Depth Returns XS: Integer {{- An Empty Element Has Depth 1 -} {- OtherWise, Add 1 To Max_u100? Epth of Children -} IF (EMPTY ($ E / *) Then 1 Else Max (for $ c in $ E / * RETURN DEPTH ($ C)) 1} The first two parts are called Query ProLog. (3) Query expression is the most important part of the module structure, for example: for $ e in document ("emp.xml") // name return $ E

XQuery syntax and instance each xQuery query includes one or more query expressions. Common XQuery syntax: Path Expression, arithmetic expression with Boolean expressions, FLWR expressions, conditional expression, element constructors, and function calls (Function Call). Path Expression XQuery, the path expression follows the syntax of XPath 2.0. They use the PATH tag to select the node of interest from the XML document. Here, it is actually seen as a tree with nodes. The path expression provides a method of selecting a node from the node tree. Some examples of path expressions are mentioned below: • PARA selection for the paragraph element of the context node? * Select all elements of the context node? Text () Select all the text nodes of the context node? @Name Selects the Name property of the context node? @ * Select all attributes of the context node? Para [1] selection of the first PARA element node of the context node? Para [Last ()] The last PARA element node of the context node is selected? * / Para selection as a PARA element of the grandson node? / Doc / chapter [5] / section [2] Select DOC Chapter 5 Part III? Chapter // Para sends the grace of the child's node of the context Node CHAPTER to choose? // Para's grandson's grandson's node PARA of all documents, and the same as the context PARA elements in a document are selected? // ilist /: item Select all item elements in the same document as a context node with an OLIST dual-proceeding point? Select the context node? .//Para selection as the context Point grandson node's para element? .. Choose a double-pro-junction point for context nodes? ./@Lang selection of LANG attributes of the double-proof point of the context node? Para [@ type = "warning"] For all PARA elements of the child node with a Type property value for Warning? Chapter [title = "introduction"] Select Chapter with Title's Introduction.? Chapter [Title] Select one or more Title's Chapter? Employee [@secretary and @ssistant] Select all the child nodes of the child's node with the secondary attribute and the assistant property of EMPLOYEE. • Book / (chapter | appendix) / section Select Book in Book is part of Chapter or Appendix. Book / XF: ID (Publisher) / Name and XF: ID (Book / Publisher) / Name Returns the same result. Arithmetic expression and boolean expression (AritiTic and Boolean Expressions): This is the easiest part, the rules are similar to the grammar. We may wish to experience a few examples: Expressions: 10 * 5 Return to the result 50.0 Expression: if (10 * 5 = 50) THEN 55 ELSE 56 Return Result: 55 Expression:

NumFormat ("####", IF (10 * 5 = 50) THEN 55 ELSE 56) Return Result: 55 Expression:

NumFormat ("###. ##", IF (10 * 5 = 50) The "55.5555" Else "56.4444")

Please note that double quotes are needed. The calculation results will return: 55.56FLWR Expression FLWR (read "FLOWER") is one of the most important syntax types of XQuery. They look similar to SQL SELECT statements and have similar functions. FLWR "Flower", represents for, let, where, and returnge expressions. Where: (1) The FOR statement combines one or more variables together, each variable will be given a series of values, which is the corresponding expression, the entire content is worth it. Cartesian product. (2) Let statement binds the variable directly to a complete expression. If the for statement exists, the variable bindings created by letters will be added to the tuple generated by the for statement. If there is no for statement, the Let statement will generate a TUPLE with all variables. (3) Where statement applies to Tuple generated by the for statement and the Let statement. (4) The return statement contains an expression that is used to generate the result of the FLWR expression. Although a complete query statement can be completed in one line, XQuery still uses a grinding program design style to increase readability. In our data query, we use the indented program design mainly echo the nesting nested. For example, the "for" statement in the input and "for" statement in the output is aligned in the vertical row. Of course, this is our programming style, you can keep your own program design style. Example: For $ e in document ("Emp.xml") // name return $ E The above example returns a element for each element. The output of the output is as follows. The actual output will depend on the specific situation of the database. Different database output formats will be different. Hari john ... leu example: Let $ E: = Document ("Emp.xml") // name return $ E An example returns a forest consisting of elements and is enclosed in a element. HARI John ... leu Need to note that the above let statement returns a correct XML document. But for the FOR statement. If this is the user's hopes, it is very good. But if the user wants to get a format neat XML document, the FOR query will be able to modify it.

for $ e in document ("Emp.xml") // name return $ E The expression on the above will return a correct XML document. Please note that the label and in this example are returned. At the same time, it should be noted that in order to make the return statement properly, a single entity must be included. HARI john ... Leu

Note that the above query is returned is the element. If we want to display the value of the name without displaying any tags? We need to use the text () function. In the above query, "// Name" is changed to "// name / text ()", "$ E" is changed to "$ E / text ()". This method is used in the following query. For $ e in document ("emp.xml") // name return $ E / text () This query returns a series of names with no labels. This shows that the xQuery query can be customized according to the situation expected by the user or the application. XQuery is developed from a language called quilt. Harijohn ... Leu has another example.

For $ d in distinct ("Emp.xml") // DNAME) Let $ E: = Document ("Emp.xml") // entry [DNAME = $ D] Return Concat ($ d / text (), "Department HAS", NumFormat ("##", count ($ E)), "Employee (s).")

The following results will be output: Credit Department Has 1 Employee (s) .toys Department Has 2 Employee (s). SHOES Department Has 1 Employee (s) .Audit Department Has 1 Employee (s).

Conditional Expression In the previous example we have initially contacted some of the IF THEN ELSE statement usage, let's take a specific look at their grammar format: if Then Else < Expression II> In condition expression, the conditional expression should assign a value of the Boolean, or a type that can be converted to the Boolean value. If the value is true, the value of the result of the entire condition is the same as the value of the expression. Otherwise and the expression of the expression. The following is a simple example of the reader:

for $ e in document ("emp.xml") // entry return $ E / NAME, IF ($ E / SALARY.> =. 60000) THEN 100000 ELSE 200000

Element Constructor When writing query statements, you may need to create a new element as part of the output. Element constructors provide such functions. An example of a simple element constructor is as follows: xQuery language The content of the new element can be specified, or it can be calculated. Function Call This is identical to the concept of functions here and function concepts in other programming languages. Let's take an example: The following function returns the maximum depth of the XML document. Then a caller of calculating a depth of PartsList.xml document. Define Function Depth Returns XS: Integer {{- An Empty Element Has Depth 1 -} {- OtherWise, Add 1 To Max Depth of Children -} IF (EMPTY ($ E / *)) THEN 1 Else Max (for $ c in $ E / * RETURN DEPTH ($ C)) 1}

Depth (Document ("Partlist.xml")))

Advanced topics and application requirements and in xQuery, ask for easy completion through Let and SUM, in SQL, use "Group By" and "Having" statement. However, in SQL, "Group By" and "Having" can only correspond to an from statement, and multiple Let statements can be used in XQuery. The following example is to return the total amount of salary in accordance with the department.

For $ d in distinct (Document ("Emp.xml") // DNAME) Let $ s: = Document ("Emp.xml") // entry [DNAME = $ D] / SALARY RETURN $ D, SUM ($ S)

If you want to get wages greater than or equal to 70000, we should do the following query. for $ d in distinct ("Emp.xml") // DNAME) Where every $ s in document ("emp.xml") // entry [DNAME = $ D] Satisfies ($ S / SALARY> = 70000) Return $ D, avg (document ("emp.xml") // entry [DNAME = $ D] / SALARY)

The most important thing worth noting is. In KWEELT, we use ".> =." Rather than use "> =" e usees ".> =." The biggest obstacle is that Kweelt does not support the word. Therefore, "Every X Satisfies C (x)" does not work in Kweelt. Imagine an equivalent expression "NOT (Some X Satisfies Not (C (X))" Although this still contains the word, it provides us with an indirect way: First we collect NOT in $ s (C (C) x) Elements X, use "not exists" in the WHERE clause to filter out some of the through For statement but does not meet this requirements. The remaining part is required, and will execute after the return statement It was released. So we got the following query. for $ d in distinct ("Emp.xml") // DNAME) Let $ s: = document ("emp.xml") // entry [DNAME = $ D and Salary. <. 70000] / Salary WHERE NOT (exists) Return $ D, avg (Document ("Emp.xml") // entry [DNAME = $ D] / salary)

This also shows the imperfectness of SQL syntax, and students in Computer Science and Technology must attach great importance to this understanding. When a thing is standardized, how much is it. The XQuery is very good at the beginning of the beginning. The imperfectness of KWeelT may be derived from the pre-standard version of XQuery. Sort sorting is performed by default. As shown in the following example: for $ I in (1, 2), $ J in (3, 4) Return {$ i} {$ j} < / tuple>

The format of the result is as follows, and the order is very important. 1 3 1 4 < I> 2 3 2 4

Of course, we can change the order for efficiency, as shown in the following example: The result is similar to the above, but the order may be different, and the system will optimize. For $ I in Unordred (1, 2), $ J in Unordered (3, 4) Return {$ I} {$ j}

Refactoring the following example, this example is about books, each book contains information about the author and publishers. TCP / IP illustrate </ title> <author> w. Stevens </ author> <publiciisher> addison-wesley </ publisher> </ book> <book> <title> Advanced Programming in The Unix Environment </ Title> <author> w. Stevens </ author> <publiciisher> addison-wesley </ publisher> </ book> </ bib> The following expressions are used to convert the input into an author list: < Authlist> {Let $ INPUT: = Document ("bib.xml") for $ a in distinct-value ($ in // author) Return <author> {<name> {$ a / text ()} </ name> , <Books> {for $ b in $ b / author = $ a return $ b / title} </ books>} </ author>} </ authlist></p> <p>It can be found that the author's name is the author's name. Each author element includes the author's name and the author's work name, which uses Distinct-Values ​​to prevent the output order from being destroyed. Here is the result of the expression output:</p> <p><authlist> <author> <book> W. Stevens </ name> <books> <title> TCP / IP illustrate </ title> <title> Advanced Programming in The Unix Environment </ Title> </ books> </ authoror > </ authlist></p> <p>The programmer prepared by the data query program should be cautiously combined with the FLWR expression with path expressions. The most important thing is that the return result of you must clear the path expression is based on the order of document, and the return result of the FLWR expression is determined by the for statement. Find the following example lists the books of more than 100, follow the first author's name to find, each author is looking for in accordance with the title. // Book [Price> 100] Sortby (Author [1], title) Sort can produce multi-level lookup results, the following query returns a list of publishers discharged in alphabetical order, contains several in each publisher element The book element, each of the number of elements contains the name and price of the book, and is arranged in descending order. <Publisher_List> {for $ P in Distinct-Values ​​("BIB.XML" // Publisher) Return <Publisher> <name> {$ p / text ()} </ name> {for $ b in Document "bib.xml") // book [publisher = $ p] return <book> {$ b / title} {$ b / price} </ book> sortby (price descending)} </ publisher> Sortby (Name)} </ publisher_list> Need to note: Sortby If you use Sortby in the path expression, it will cause unpredictable results. Let's analyze the following example:</p> <p>(Employees Sortby (Salary) / Name You may think that the result of the returned query must be the name of the employee arranged in accordance with the employee's income. However, the path expression always returns a node sequence according to the document order. Therefore, the result of this query is the list of employee names arranged in accordance with the document sequence. If the name sequence you want is output according to the salary sequence, the query should be as follows: For $ e in (Employees Sortby) Return $ E / NAME Filter Filter Filter ($ doC // (A | B) )) Returns a forest. • Filter out from the $ doc is not the node of the A and C class. ? Protection A class nodes and the relationship between Class B.</p> <p>Before performing filter: $ doc executes filtered: FILTER ($ DOC / / (A | B)) The following example uses filtration to return to the catalog of the cookbook.xml file.</p> <p><TOC> {Filter (Document ("cookbook.xml") // (section | section / title | section / title / text ())} </ toc></p> <p>The query XQuery in the sequence uses Precedes, Follows, <<, and >> operators to represent sequence relationships. This part of the query contains a surgical report that includes procedure, an Incision, and anesthesia. The following query returns the first operation of the first process and the elements and node sequences of the second surgical.</p> <p><critical-sequence> {let $ proc: = // procedure [1] for $ n in $ proc // node () Where $ n Follows [1] and $ n Precedes ($ proc / / incision [2] return $ n} </ critical-sequence> spj query: Employee and administrators have an example: <EmpandManagers> For $ e in document ("emp.xml") // entry for $ M in document ("dept.xml") // entry where $ e / dname = $ m / dname return <Empmanager> $ E / NAME, $ m / mname </ EmpManager> Sortby (Name Descending) </ EmpandManagers></p> <p>The query will return to the XML document Document below. <EmpandManagers> <Empmanager> <name> Mary </ name> <mname> Mary </ mname> </ EmpManager> <EmpManager> <name> Leu </ name> <mname> leu </ mname> </ EmpManager> < Empmanager> <name> john </ name> <mname> Mary </ mname> </ empManager> </ empandManagers></p> <p>Here is another writing method for querying. <EmpandManagers> For $ e in document ("emp.xml") // entry for $ m in document ("dept.xml") // entry [DNAME = $ E / DNAME] / MNAME RETURN <EmpManager> $ E / Name, $ M </ EmpManager> Sortby (Name Descending) </ EmpandManagers></p> <p>What should we do if we consider using a Let statement instead of the second for statement? Let's look at the query below. <EmpandManagers> For $ e in document ("emp.xml") // entry let $ m: = document ("dept.xml") // entry [DNAME = $ E / DNAME] / MNAME RETURN <EmpManager> $ E / Name, $ M </ EmpManager> Sortby (Name Descending) </ EmpandManagers></p> <p>In the first two queries with For statement nested, the for statement inside did not find any matching sectors, and there was no report for this employee. Now in this original second place uses a Let statement, the variable will be an empty manager. This is not a failure, empty manager will be reported. The results are shown below. Please note that Employee without Manager is also listed, but because such Employee does not match the elements in the departmental relationship. Therefore, <manager> elements will be omitted simply. What will be like when there is no manager in the departmental relationship? In this case, it will be the element of "<manager> </ manager>" will also appear in the query results. <EmpandManager> ... <EmpManager> <name> John </ name> <manager> Mary </ manager> </ empManager> <EmpManager> <name> HARI </ name> </ EmpManager> </ EmpandManagers></p> <p>Information without Manager can filter out: <EmpandManagers> for $ e in document ("emp.xml") // entry let $ m: = document ("dept.xml") // entry [DNAME = $ E / DNAME] / MNAME RETURN IF (EXISTS ($ M)) Then <EmpManager> $ E / NAME, $ M </ EmpManager> Else "" Sortby (Name Descending) </ EmpandManagers></p> <p>With a similar approach we can filter out Employee information with Manager, you can use the following statement: "NOT (exists)". It should be noted that XQuery provides more options when compared to the SQL language. When the user has a preliminary idea for how to make a query, it will succeed. It is also important to pay attention to whether orientation seems to be more symmetrical. Subqueries performed in SQL can be done as long as the LET expression is used.</p> <p>According to the department recombination Emp.xml Document Employee Record is organized according to <Name> element. Even in the department may have multiple employees, this is not complicated in XML. The following example shows how to complete the above features with the query method. <DeptsAndemps> for $ d in distinct ("Emp.xml") // DNAME) Return <DePTList> $ D, <Empslist> for $ E in Document ("Emp.xml") // entry [DNAME = $ D] Return <namesal> $ E / NAME, $ E / SALARY </ Namesal> </ Empslist> </ DePTList> </ deptsandemps></p> <p>The results of the query are as follows: <DeptsAndemps> <DePTList> <DNAME> CREDIT </ DNAME> <Empslist> <Namesal> <name> HARI </ Name> <Salry> 55000 </ SALARY> </ Namesal> </ Empslist > </ Deptlist> <dePTList> <DNAME> Toys </ dname> <Empslist> <name> <name> john </ name> <salary> 80000 </ salary> </ name> <name> <name> Mary < / Name> <Salary> 90000 </ SALARY> </ namesal> </ empslist> </ deptlist> ... </ deptsandemps> XQuery and SQL comparison first let's see two examples: SQLSELECT PNOFROM PWHERE DESCRIP LIKE 'GEAR % 'Order by PNO; SELECT PNO, AVG (Price) as avgpricefrom spgroup by pnohaving count (*)> = 3ORDER BY PNO;</p> <p>XQueryfor $ P in Document ("p.xml") // p_tuplewhere Starts-with ($ P / Descrip, "Gear") Order by $ P / PNO Return $ P / PNO for $ PN IN DISTINCT-VALUES (Document (" SP.XML ") // pno) Let $ sp: = document (" sp.xml ") // sp_tuple [pno = $ pn] where count ($ sp)> = 3ORDER BY $ PNRETURN <Well_suPPLIED_ITEM> {$ PN, <avgprice> {avg ($ sp / price)} </ avgprice>} <Well_supplied_Item> We can see through the above two examples, both have a similar point, there are many different, as two mainstream query languages We can make a comparison to both: SQL is known to the operation mode of the relational database, and there is already a corresponding strategy. Use SELECT, FROM, WHERE, Group BY, and HAVING statement command relationship Properties Tuple full XML document with tuple variables instead of tuple only with a group variable in each Select statement in WHERE statement filtering Tuple, group by and having The statement can handle Group. Just a single attribute subquerix can be used for the WHERE statement syntax form, but only returns a relationship SELECT statement returns a simple value</p> <p>XQuery is an operation mode for an XML document is not necessary. The future mode can be used to verify and perform xQuery queries. Use the for-let, where and return expressions, from the from, where and succut statements in SQL. In XQuery, you do not need Group BY and HAVING statements. Single XML element</p> <p>The FOR variable represents an element (a sub-tree) Let variable representing a series of elements (a forest) can have multiple for and let variables where statement can be used to filter one element defined by for and letters or one Elements. The LET variable can be used to create any number of similar packet mechanisms. There is no such requirement in XQuery. In XQuery, you can use it with a simple clear syntax structure at any time you need to use subqueries. It is available in conjunction with ordinary syntax. Also included, if Then Else, aggregation, and numerical words can return an XML document or even a simple text document RetURN statement allows elements to be adjusted to arbitrarily as a result output.</p> <p>XQuery's implementation and application XQuery as a new data query language has been accepted and adopted by many research institutions and companies. At present, Microsoft, IBM and Oracle's database cores are all XQuery standards. IBM's XPeranto-based Information Integrator integrates XML, XQuery, file search technology and Web Services technology. It is possible to query data in relational databases, XML files, general files, spreadsheets, and other data sources, as in a single database. The Liquid Data launched by BEA is an engine and visualization tool based on XML and XQuery, which can connect data sources of different locations, including tables, files, and audio and video materials. Can accelerate information integration and integration between enterprises and partners. Oracle issued a Java XQuery prototype standard in March 2002, now we can get the latest download by the following address: The latest version is release_0.2_030217 when this article is old, which is a technology preview. http://otn.oracle.com/sample_code/tech/xml/xmldb/xmldb_xquerydownload.html contains a JAR file with an Oracle XQuery prototype (in a JAR file) and a Java document. Once the installation is complete, you can use the Java API (OJXQI) or the command line utility to test the prototype. Running this prototype requires some of the most basic environments, such as XDK, the lowest version requires XDK 9i Production Release - XDK 9.2.0.1.0. Also JDK, the lowest version is JDK 1.3, if you want to access the database, you need to use Oracle XSU and JDBC driver. After extracting the XQuery file, you need to set the environment variable, we assume that the XQuery folder is compressed to the root directory of the C drive, then the operation of the environment variable is as follows: classpath = c: /xQuery/xQuery.jar; c: / xdk / lib / lib /XMLPARSERV2.JAR; if the setting is completely no problem, you should now have an XQuery query. Due to the example of the Oracle official download package XQuery prototype appears like some problems, we have some modifications on this basis, got the following test programs:</p> <p><bib> {for $ b in Document ("BIB.XML") / BIB / BOOK WHER $ b / Publisher = "addison-wesley" and $ b / @ Year> 1991 Return <book> {$ b / @ Year} {$ B / TITLE} </ book>} </ bib></p> <p>Switch to the command line state, enter the folder of XQuery.jar, and let's enter in the command: Java Oracle.xQuery.xqlpluse ExMpl2.xql will return the following query results from the command line: Another interaction The method of style, the author feels not perfect, so it is not an introduction. If you want to know about Oracle's online documentation. The technical features are to implement the XQuery standard of W3C and plus Oracle extension, and focus on relational databases and xQuery use cases, another feature is a JDBC Java API for XQuery, which contains an experimental JDBC. And like SQL's function, you can use XQuery on SQL query results. Oracle's goal is to provide a Query syntax for both SQL style and xQuery-based to query XML data in the Oracle database. Oracle 9i also supports XML Schema, which can be used to access data in the original relational database with an XML format to become a Native XML database. The latest Oracle 10G has further strengthened support for XQuery. Microsoft has been introduced in the XML Query Language Demo network in May 2001, you can access: (http://131.107.228.20). You can use the above example to perform query demonstration, you can also write the XQuery query program yourself. Let's take a look at a specific demonstration query:</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-82119.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="82119" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.039</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'VYm9SqSj_2ByE7R1qpxKrAKscPHEheQo3BnnMEuq7BvO5wyiZAjZBMvCrTj5oOXLWv3n7553guFhO2IGMVSLbfaw_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>