XPath syntax example in C #

Source: Internet
Author: User

XPath can quickly locate nodes or attributes in XML. The XPath syntax is simple, but powerful enough. It is also the basic knowledge of using XSLT.

Example XML:

<?xml version="1.0" encoding="utf-8" ?><pets>  <cat color="black" weight="10">    <price>100</price>    <desc>this is a black cat</desc>  </cat>  <cat color="white" weight="9">    <price>80</price>    <desc>this is a white cat</desc>  </cat>  <cat color="yellow" weight="15">    <price>80</price>    <desc>this is a yellow cat</desc>  </cat>  <dog color="black" weight="10">    <price>100</price>    <desc>this is a black dog</desc>  </dog>  <dog color="white" weight="9">    <price>80</price>    <desc>this is a white dog</desc>  </dog>  <dog color="yellow" weight="15">    <price>80</price>    <desc>this is a yellow dog</desc>  </dog></pets>

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+ The plus sign indicates that the plus sign (-) indicates that the number is subtracted. * multiplied by the DIV indicates that the number is divided by. Here, the mathematical division sign/has been used as a separator between nodes. Mod indicates that the remainder is obtained. 3. XPath logical operators= Equals, equivalent to =! in C! = Not equal to> greater than> = greater than or equal to <less than <= less than or equal to and with 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:

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 two: Position () indicates the node sequence number. For example, // cat [position () = 2] indicates the last () of the dog node whose serial number is 2 () it indicates getting the last node // cat [last ()] Name () indicates the name of the current node/pets/* [name ()! = 'Pig'] There are many functions, including string functions, numeric functions, and time functions, that are not pig subnode XPath functions under/pets. For details, refer to 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 = @ "<? XML version = "" 1.0 "" encoding = "" UTF-8 ""?> <Pets> <cat color = "black" "Weight =" 10 "" Count = "4" "> <price> 100 </price> <DESC> This is A black cat </DESC> </CAT> <cat color = "" White "" Weight = "9" "Count =" 5 ""> <price> 80 </price> <DESC> This is a white cat </DESC> </CAT> <cat color = "" yellow "" Weight = "15" "Count =" "1 ""> <price> 110 </price> <DESC> This is a yellow cat </DESC> </CAT> <dog color = "black" "Weight = "" 10 "" Count = "7" "> <price> 114 </price> <DESC> This is a black dog </DESC> </dog> <dog color = "" White "" Weight = "9" "Count =" 4 "> <price> 80 </price> <DESC> This is a white dog </DESC> </dog> <dog color = "" yellow "" Weight = "15" "Count =" "15" "> <price> 80 </price> <DESC> This is a yellow dog </DESC> </dog> <pig color =" "White" "Weight = "" 100 "" Count = "2" "> <price> 8000 </price> <DESC> This is a white pig </DESC> </pig> </pets> "; using (stringreader RDR = new stri Ngreader (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. selectsinglenode (".. "); // select weight * count = 40. 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 Div @ 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. Price xmlnodelist childrennodes = Doc. selectnodes ("Descendant: price");} console. read ();}}}

C # processing XML:

1. read and Write XML documents through xmldocument 2. use xmlreader to read XML, use xmlwriter to write xml3. use LINQ to XML to access xml4. use xmlscheme to define fixed-format XML documents. 5. XML serialization or deserialization Class 6. search for XML nodes using XPath 7. convert XML format using XSLT

XPath syntax example in C #

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.