XPath queries XML in ASP.

Source: Internet
Author: User
Tags cdata processing instruction types of functions xpath contains

In the. NET Framework 2.0, you can use the classes under the System.Xml.XPath namespace to make path-based queries to an XML document, and you need to construct a SQL-like query string that follows the XPath syntax during the query process. It is used by the two methods in the following table to avoid traversing the entire tree of XML documents.

Method name Description
selectSingleNode This method is used to select a node. If you create a query that finds multiple nodes, only the first node is returned
SelectNodes This method returns a collection of nodes in the form of a xmlnodeslist class

Test.cs
=====================================================
Using System;
Using System.Xml.XPath;

Class Test
{
       public static void Main (string[] args)
        {
           xpathdocument doc = new XPathDocument (@ "./test.xml");
           XPathNavigator nav = doc. CreateNavigator ();
           nav. Evaluate (" Here you need a query path that follows the XPath syntax ");
       //When the above method executes, the query results are returned and can be converted to the appropriate data type.
          //For specific details and examples, please refer to MSDN2005 for System.Xml.XPath naming
          //Space section, detailed description.
      }
}

Test.xml
=====================================================
<?xml version= "1.0" encoding= "Utf-8"?
<a id= "A1",
     <b id= "B1";
       <c id= "C1";
         <b name= "B"/>
          <d id= "D1"/>
         <e id= "E1 "/>
         <e id=" E2 "/>
        </c>
     </b>
     <b id= "B2"/>
      <c id= "C2",
       <b/>
        <d id= "D2"/>
       <f/>
      </c>
     <e/>
</a>

The first thing to say is the XPath data type. XPath can be divided into four types of data:

Node Set (node-set)

A node set is a collection of a set of nodes that are returned by a path match that matches the criteria. Other types of data cannot be converted to node-sets.

Boolean Value (Boolean)

The condition-matching value returned by a function or Boolean expression is the same as a Boolean value in a generic language, with a value of true and false two. Boolean values can be converted to and from numeric types, string types.

Strings (String)

A string is a collection of a series of characters, and a series of string functions are provided in XPath. Strings can be converted to data of numeric types, Boolean types, and other values.

Value (number)

In XPath, the value is a floating-point number, which can be a double-precision 64-bit floating point. Also includes a number of special descriptions, such as non-numeric Nan (not-a-number), positive infinity infinity, negative infinity-infinity, plus or minus 0, and so on. The integer value of number can be obtained from the function, and the value can be converted to Boolean type and string type.

The latter three data types are similar to the corresponding data types in other programming languages, except that the first data type is a unique product of the XML document tree.

Also, because XPath contains a series of operations on the document tree, it is also necessary to figure out the XPath node type. Recall the logical structure of the XML document described in Chapter Two, where an XML file can contain logical features such as elements, CDATA, annotations, processing instructions, which can also contain attributes, and can use attributes to define namespaces. Accordingly, in XPath, the nodes are divided into seven types of nodes:

root node (rooted)

The root node is the topmost layer of a tree, and the root node is unique. All other element nodes on the tree are its child nodes or descendant nodes. The root node is treated the same as the other nodes. Matching a tree in XSLT always begins with the root node.

Elements node (element Nodes)

ELEMENT nodes correspond to each element in the document, and the child nodes of an element node can be element nodes, annotation nodes, processing instruction nodes, and text nodes. You can define a unique identity ID for an element node.
An element node can have an extension, which is made up of two parts: a namespace URI, and a local name for the other part.

Text node (Nodes)

A text node contains a set of character data, which is the characters contained in CDATA. No single text node will have an adjacent sibling text point, and the text node does not have a name extension.

Attribute node (Attribute Nodes)

Each element node has an associated collection of attribute nodes, which are the parent node of each attribute node, but the attribute node is not a child of its parent element. That is, by finding the child nodes of an element can match the attribute node of the element, but the reverse is not true, just one-way. Again, the element's attribute node is not shared, meaning that different element nodes do not share the same attribute node.
The processing of the default property is equivalent to the defined property. If a property is declared in a DTD but declared as #implied, and the attribute is not defined in the element, the attribute is not included in the element's attribute node set.

In addition, attribute nodes that correspond to properties do not have a namespace declaration. A namespace property corresponds to another type of node.

Namespace node (Namespace Nodes)

Each element node has a related set of namespace nodes. In an XML document, namespaces are declared through reserved properties, so in XPath, the class node is very similar to the attribute node, the relationship between them and the parent element is unidirectional and is not shared.

Processing instruction node (processing instruction Nodes)

The processing instruction node corresponds to each processing instruction in the XML document. It also has an extension, where the local name of the extension points to the processing object, and the namespace part is empty.

Note Node (Comment Nodes)

Note nodes correspond to comments in the document.

<a id= "A1" >
<b id= "B1" >
<c id= "C1" >
<b name= "B"/>
<d id= "D1"/>
<e id= "E1"/>
<e id= "E2"/>
</C>
</B>
<b id= "B2"/>
<c id= "C2" >
<B/>
<d id= "D2"/>
<F/>
</C>
<E/>
</A>

Now, let's introduce some basic methods of node matching in XPath.

  1. Path Matching
    Path matching is similar to the file path representation, which is better understood. There are several symbols:
    Symbol Meaning For example Match Results
    / Indicates the node path /a/c/d Child node "D" of Node "a" of child node "C", i.e. D node with ID value D2
    / Root node
    // All paths end With "//" after specified sub-path element E All e elements, the result is all three e elements
    c/e All of the parent nodes are e elements of C, and the result is two e elements with ID values of E1 and E2
    * Wildcard characters for a path /a/b/c/* A element →b all child elements under the element →c element, that is, the B element with the name value B, the D element with the ID value D1, and the two E elements with the ID value E1 and E2
    /*/*/d It has a D element with a level two node, and the matching result is a D element with an ID value of D2
    //* All the Elements
    | Logical OR B | C All B elements and C elements

  2. Location Matching
    For each element, its individual child elements are ordered. Such as:
    For example Meaning Match Results
    /A/B/C[1] The first child element of the element →c element of element a →b The B element with the name value B
    /a/b/c[last ()] A element →b element →c The last child element of the element An e element with an ID value of E2
    /a/b/c[position () >1] element with position number greater than 1 under element →c element →b elements A D element with an ID value of D1 and two E elements with an ID value

  3. Properties and properties
    In XPath, you can use attributes and attribute values to match elements, and be aware that the attribute name of an element must be preceded by an "@" prefix. For example:
    For example Meaning Match Results
    b[@id] All B elements with a property ID Two b elements with ID values of B1 and B2
    B[@*] All B elements that have attributes Two b elements with id attribute and one with Name attribute b element
    B[not (@*)] All B elements that do not have attributes Element B under Element a →c
    b[@id = "B1"] The B element with an ID value of B1 The b element under a element

      
  4. Kinship Matching
    XML documents can be attributed to a tree structure, so no one node is orphaned. Usually we boil down the relationship between the nodes as a kinship, such as fathers, children, ancestors, descendants, brothers and so on. These concepts can also be used when matching elements. For example:
    For example Meaning Match Results
    E/parent::* Parent node element for all E-nodes A element with an ID value of A1 and a C element with an ID value of C1
    F/ancestor::* Ancestor node elements of all F elements A element with an ID value of A1 and a C element with an ID value of C2
    /a/child::* Child elements of a The ID value is b1, the B element of B2, the C element with the ID value C2, and the e element without any attributes
    /a/descendant::* All descendant elements of a All other elements except the A element
    F/self::* All F's own elements The F element itself
    F/ancestor-or-self::* All f elements and its ancestor node elements f element, parent node of f element, c element and a element
    /a/c/descendant-or-self::* All a element →c elements and their descendant elements The C element with the ID value C2, the element's child elements B, D, F elements
    /a/c/following-sibling::* A element of the →c element immediately after the next post all sibling node elements The e element without any attributes
    /a/c/preceding-sibling::* A element →c the immediate front of all sibling node elements Two b elements with ID values of B1 and B2
    /a/b/c/following::* All elements of a →b element →c element b Elements with ID b2, c elements without attributes, B elements without attributes, D elements with ID D2, F elements without attributes, E elements without attributes.
    /a/c/preceding::* All elements in front of a element →c element b element with ID B2, e element with ID E2, e element with ID e1, D element with id D1, b element with name B, c element with ID C1, b element with ID B1

  5. Condition matching
    Conditional matching is a Boolean value that uses the results of some functions to match a node that matches a condition. There are four types of functions commonly used for conditional matching: node function, string function, numeric function, Boolean function. For example, the last (), position (), etc. mentioned above, we will not dwell on this.

There are some examples of XPath demonstrations:

Positioning nodes
XML is a tree structure, similar to the structure of the File system folder, XPath is similar to the file system of the path naming method. The XPath is a pattern, you can select the XML file, the path matches all the nodes of a pattern. For example, to select all the price elements in the CD under catalog can be used:
/catalog/cd/price


If the start of the XPath is a diagonal line (/) that represents this is the absolute path. If the opening is two diagonal lines (//), all elements in the file that conform to the pattern will be selected, even if the different layers in the tree are chosen. The following languages select all the elements in the file that are called CDS (which are selected in any hierarchy in the tree):
Cd


Select an unknown element
You can select unknown elements using the Star (wildcards,*). The following language will select all the child elements of/CATALOG/CD:
/catalog/cd/*


The following language will select all the child elements of the catalog, including the element with the price as a child element.
/catalog/*/price


The following language will choose to have two parent nodes, called all elements of price.
/*/*/price


The following languages will select all the elements in the file.
//*


It is important to note that in order to access non-hierarchical elements, the XPath language must be opened with two diagonal lines (//), to access unknown elements only with the Star (*), the star can only represent unnamed elements, not the unknown level of elements.
Select Branch
You can select branches using the brackets. The following language removes the first element, called a CD, from the child elements of the catalog. There is no No. 0 element in the definition of XPath.
/CATALOG/CD[1]


The following language selects the last CD element in the catalog: (XPATHJ does not have the definition first () This type of function oh, in the example of [1] can be taken out of the initial element.
/catalog/cd[last ()]


The following language selects all/CATALOG/CD elements that contain the price sub-element.
/catalog/cd[price]


The following language selects all/CATALOG/CD elements of the price element equal to 10.90
/CATALOG/CD[PRICE=10.90]


The value of the price element is selected in the following language for all/CATALOG/CD elements of the price element equal to 10.90
/catalog/cd[price=10.90]/price


Select more than one path
Using an OR operator (|) You can select more than one path. For example:
/catalog/cd/title | Catalog/cd/artist


Selects all title and artist elements
Title | Artist


Selects all title and artist and price elements
Title | Artist | Price


Select a sex
In XPath, in addition to the selection of elements, you can also select a component. The sex is at the beginning of the @. For example, all of the options in the file called country are:
@country


Select all CD elements that contain country:
cd[@country]


The following languages select all of the CD elements that contain
Cd[@*]


The following language selects the CD element for the country value of UK
cd[@country = ' UK ')

XPath queries XML in ASP.

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.