The existing XML file contains the following content:
<? XML version = "1.0" encoding = "UTF-8"?> <Company> <Department> <Name> IT department </Name> <Manager> pig 3 </Manager> <employees> <employee> <ID code = "001"> 10001 </ id> <Name> Simon Qing </Name> <gender> male </gender> </employee> <ID code = "002"> 10202 </ID> <name> Pan Jinlian </Name> <gender> female </gender> </employee> </employees> </Department> </company>
The employee node whose name is "Ximen Qing" needs to be obtained and implemented using XPath as follows:
Xmldocument xmldoc = new xmldocument (); xmldoc. load (path. combine (environment. currentdirectory, "demo. XML "); xmlnode EMP = xmldoc. selectsinglenode ("/Company/department/employees/employee [name = 'ximenqing']"); // EMP is the located employee node.
To obtain the employee node whose code is 002, use XPath to implement the following:
XmlDocument xmlDoc = new XmlDocument();xmlDoc.Load( Path.Combine( Environment.CurrentDirectory, "demo.xml" ) );XmlNode emp = xmlDoc.SelectSingleNode( "/Company/Department/Employees/Employee/ID[@code='002']/parent::node()" );
Introduction to XPath path finding
XML file is a tree structure, and XPath is a pattern for path search of XML files. For example, the XML data starting with "1" is described as follows:
/Company/Department/Employees/Employee
The beginning of xpath is a slash (/) indicating the absolute path.
- Retrieve all names, not hierarchical
//Name
A pattern in which XPath starts with //, indicating unlimited Layers
- Use*Match the element with an unknown name (unknown level cannot be matched)
1. Get all the employees
/Company/Department/Employees/*
2. Obtain the node with the employee ID as a subnode under the department.
/Company/Department/*/Employee
The element index in XPath is from1Start
Select the first employee
/Company/Department/Employees/Employee[1]
Select the last employee
/Company/Department/Employees/Employee[last()]
Select the employee named Ximen Qing
/Company/department/employees/employee [name = 'ximenqing']
Use | or for Path Selection
/Company/Deparment/Manager | /Company/Deparment/Name
Attribute in XPath, starting @
Select All Code attributes