C # uses XPath to find XML node information

Source: Internet
Author: User
Tags xml example xpath

XPath is a powerful, but also relatively complex technology, it is best to go to the blog Park to find some professional posts to look at, here are some simple XPath syntax and an example, to provide you with reference.

XML Example:

<?XML version= "1.0" encoding= "Utf-8"?><Roles>  <roleOrder= "1">    <Roleid>1</Roleid>    <RoleName>General users</RoleName>  </role>  <roleOrder= "3">    <Roleid>2</Roleid>    <RoleName>Test user</RoleName>  </role>  <roleOrder= "2">    <Roleid>3</Roleid>    <RoleName>Center Administrator</RoleName>  </role>  <roleOrder= "4">    <Roleid>4</Roleid>    <RoleName>System administrator</RoleName>  </role></Roles>

Description: If the beginning of the XPath is a slash (/) represents this is the absolute path. If the beginning is a two slash (//) indicates that all conforming elements in the file will be selected, even at different levels in the tree

1. Select the rolename of the first role

Example:/roles/role[1]/rolename Description: The subscript in XML is starting with 1

2. Select the node for the role of attribute order= ' 2 '

Example:/roles/role[@order = ' 2 ') Description: @order represents a property

3. Select the value of the order of the first role

Example:/roles/role[1]/@order

Summary: The above is the XPath syntax, but how to use it in C #, the code is as follows:

New XmlDocument ();  // instantiate a XmlDocument XML. Load ("app.xml");        // to load an XML document from a path // The index in XML starts at 1 XmlNode node=xml. selectSingleNode ("/roles/role[1]/@order");    Depending on the XPath that returns a specific node, if there are multiple nodes that match, the first node is returned, and the selectnodes () term obtains a collection of multiple nodes MessageBox.Show (node. InnerText);    // read the information about the node

C # uses XPath to find XML node information

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.