Xml learning (6) in the c # Xpath instance

Source: Internet
Author: User
Tags xpath functions
In c #, we often search for and traverse nodes. we can use the XPath syntax. The XPath syntax is simple, but powerful enough. XPath can quickly locate nodes or attributes in Xml, it is also the basic knowledge of using xslt. Reprinted :#

In c #, we often search for and traverse nodes. we can use the XPath syntax,The XPath syntax is simple, but powerful enough,XPath can quickly locate nodes or attributes in Xml.It is also the basic knowledge of using xslt

Example Xml:

   
   
    
   
    100
     
   
    this is a black cat
     
    
    
   
    80
     
   
    this is a white cat
     
    
    
   
    80
     
   
    this is a yellow cat
     
          
    
   
    100
     
   
    this is a black dog
     
    
    
   
    80
     
   
    this is a white dog
     
    
    
   
    80
     
   
    this is a yellow dog
     
    
 

XPath syntax:

1. symbols in XPath

Symbol

Description

Example

Example

/

Indicates selecting from the root node

/Pets

Select the root node pets

The delimiter between a node and a subnode.

/Pets/dog

Select the dog node under the pets node

// Xx

Indicates to search the entire xml file, regardless of the current node location.

// Price

Select all price nodes in the document

.

Select the current node

/Pets /.

Select pets node

..

Dual-vertex, indicating that the parent node is selected

/Pets/dog [0]/..

Indicates the pets node, that is, the parent node of the first dog node.

@ Xx

Select attribute

// Dog/@ color

Specifies the set of color attributes of all dog nodes.

[…]

Brackets indicate selection conditions, and brackets indicate conditions.

// Dog [@ color = 'white']

All dog nodes whose color is white

// Dog [/price <100]

All dog nodes whose price point value is less than 100

The numbers in the brackets are node indexes, similar to arrays in c # and other languages. the array subscript starts from 1.

// Dog [1]

1st dog nodes

// Dog [last ()]

Last dog node. last () is the built-in function of xPath.

|

Single vertical bars indicate combined nodes

// Dog [@ color = 'white'] | // cat [@ color = 'white']

Dog nodes whose color attribute is white and cat nodes whose color attribute is white

*

Asterisk indicates the node or attribute of any name

// Dog /*

Indicates all child nodes of the dog node.

// Dog /@*

Indicates all attribute nodes of the dog node.


2. XPath mathematical operators

+ Plus sign indicates addition

-Subtraction of numbers

* Multiply

P indicates dividing by. here, the mathematical division/has been used as a separator between nodes.

Mod indicates the remainder.

3. XPath logical operators

=, Equivalent to = in c #

! = Not equal

> Greater

> = Greater than or equal

<Less

<= Less than or equal

And relationship

Or relationship

4.XPath AxesThis is the meaning of the XPath axis, but according to my understanding, it is more appropriate to translate it into the keyword of the XPath node link operation, that is, a set of keywords plus :: A double colon represents one or more nodes related to the current node.

Syntax: axisname: nodetest [predicate]: Axis name: node name [obtain node conditions]

The details are as follows:

Keywords

Description

Example

Example

Ancestor

Parent node of the current node

Ancestor: pig

Pig node in the current node's ancestor node

Ancestor-or-self

Current node and its parent node

Ancestor: pig

Attribute

All attributes of the current node

Attribute: weight

Equivalent to @ weight, attribute: is equivalent @

Child

All byte points of the current node

Child: * [name ()! = 'Price']

Select a subnode whose name is not price

Descendant

Child node

Descendant: * [@ *]

Child nodes with attributes

Descendant-or-self

Child node and current node

Descendant-or-self ::*

Following

All nodes after the current node in the Xml document

Following ::*

Following-sibling

The same parent node of the current node

Following-sibling ::

Preceding

All nodes before the current node in the Xml document

Preceding ::*

Namespace

Select all namespace nodes of the current node

Namespace ::*

Parent

Parent node of the current node

Parent ::

It is equivalent to a pair of vertices ..

Preceding-sibling

Same parent node after current node

Preceding-sibling ::*

Self

Current node

Self ::*

It is equivalent to a single point.


5. Introduction to common XPath functions:

Common functions in XPath expressions include the following:

Position () indicates the node sequence number. for example, // cat [position () = 2] indicates the dog node whose serial number is 2.

Last () indicates getting the last node // cat [last ()]

Name () indicates the name of the current node/pets/* [name ()! = 'Pig'] indicates that the child node under/pets is not pig.

There are many other XPath functions, including string functions, numeric functions, and time functions. for details, refer to the w3 website.

The above is the XPath syntax. let's take a look at how to use XPath in. Net.

In. Net, you can use XPath through the XPathDocument or XmlDocument class. XPathDocument is read-only to locate Xml nodes or attribute texts, while XmlDocument is readable and writable.

The following code example shows how to use XPathDocument and XmlDocument.


Using System; using System. collections. generic; using System. linq; using System. text; using System. xml. XPath; using System. xml; namespace UseXPathDotNet {class Program {static void Main (string [] args) {UseXPathWithXPathDocument (); UseXPathWithXmlDocument (); Console. read ();} static void UseXPathWithXmlDocument () {XmlDocument doc = new XmlDocument (); doc. load (" http://www.cnblogs.com/yukaizhao/rss "); // Use xPath to select the desired node XmlNodeList nodes = doc. selectNodes ("/rss/channel/item [position () <= 10]"); foreach (XmlNode item in nodes) {string title = item. selectSingleNode ("title "). innerText; string url = item. selectSingleNode ("link "). innerText; Console. writeLine ("{0 }={ 1}", title, url) ;}} static void UseXPathWithXPathDocument () {XPathDocument doc = new XPathDocument (" http://www.cnblogs.com/yukaizhao/rss "); XPathNavigator xPathNav = doc. createNavigator (); // use xPath to obtain the latest 10 XPathNodeIterator nodeIterator = xPathNav. select ("/rss/channel/item [position () <= 10]"); while (nodeIterator. moveNext () {XPathNavigator itemNav = nodeIterator. current; string title = itemNav. selectSingleNode ("title "). value; string url = itemNav. selectSingleNode ("link "). value; Console. writeLine ("{0 }={ 1}", title, url );}}}}

For an example of using XPath, see the following code annotations.

Using System; using System. collections. generic; using System. linq; using System. text; using System. IO; using System. xml; namespace UseXPath1 {class Program {static void Main (string [] args) {string xml = @"
 
 
  
   
    
100
   
   
    
This is a black cat
   
  
  
   
    
80
   
   
    
This is a white cat
   
  
  
   
    
110
   
   
    
This is a yellow cat
   
    
  
   
    
114
   
   
    
This is a black dog
   
  
  
   
    
80
   
   
    
This is a white dog
   
  
  
   
    
80
   
   
    
This is a yellow dog
   
   
  
   
    
8000
   
   
    
This is a white pig
   
  
 "; Using (StringReader rdr = new StringReader (xml) {XmlDocument doc = new XmlDocument (); doc. load (rdr); // Get the dog byte points of all pets nodes XmlNodeList nodeListAllDog = doc. selectNodes ("/pets/dog"); // All price nodes XmlNodeList allPriceNodes = doc. selectNodes ("// price"); // get the last price node XmlNode lastPriceNode = doc. selectSingleNode ("// price [last ()]"); // use the two-point number to obtain the price node's parent node XmlNode lastPriceParentNode = lastPriceNode. selectSingl ENode (".. "); // select all animals with weight * count = 40 and use the wildcard * XmlNodeList nodeList = doc. selectNodes ("/pets/* [@ weight * @ count = 40]"); // select all animals except pig and use name () the function returns the node name XmlNodeList animalsExceptPigNodes = doc. selectNodes ("/pets/* [name ()! = 'Pig'] "); // Select an animal whose price is greater than 100 instead of pig XmlNodeList priceGreaterThan100s = doc. selectNodes ("/pets/* [price p @ weight> 10 and name ()! = 'Pig'] "); foreach (XmlNode item in priceGreaterThan100s) {Console. writeLine (item. outerXml);} // select the second dog node XmlNode theSecondDogNode = doc. selectSingleNode ("// dog [position () = 2]"); // use xpath to obtain the parent node XmlNode parentNode = theSecondDogNode from the axes parent. selectSingleNode ("parent: *"); // use xPath to select all dog nodes before the second dog node XmlNodeList dogPresibling = theSecondDogNode. selectNodes ("preceding: dog"); // retrieve all child nodes of the document priceXmlNodeList childrenNodes = doc. selectNodes ("descendant: price");} Console. read ();}}}

The above is the content of xml learning (6) in the c # Xpath instance. For more information, see PHP Chinese network (www.php1.cn )!

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.