------------------- XML Code <employees> <employee name = "Li yuqiu" age = "23"> <address> No. 178 Changjiang Road </address> <Department> singing Department </Department> </employee> <employee name = "Zeng "age = "24"> <address> No. 239, Mars road </address> <Department> dance department </Department> </employee> <employee name = "Zhang xueenemy" age = "27"> <address> No. 13, Hong Kong Street </address> <Department> idol Department </Department> </employee> </ employees> -------------- for example: to obtain the ADDR under the node name = "Once unavailable" The ESS node value is "No. 239, Mars Road". C # How to implement it?
OK. Before using LINQ, you can try xmldocment to read the entire XML file, and then use XPath for analysis.
Since the advent of LINQ, everything has become simple and implemented.CodeAs follows:
// Assume that the above XML is saved in a local XML file D: \ microsoft work \ xmlpath \ samplexml. in XML, public list <string> getxmlresult () {xelement = xelement. parse (@ "D: \ microsoft work \ xmlpath \ samplexml. XML "); var query = xelement. descendants ("employee "). where (x => X. attribute ("name "). value = "Once unavailable "). select (x => X. element ("Address "). value); If (query! = NULL & query. Count ()> 0) return query. tolist <string> (); return NULL ;}
In this way.
OK. Now let's make a slight change to the above XML structure,
------------------- XML Code
Yangtze River
No. 178 Changjiang Road
singing Department
Mars
No. 239, Mars road
dance department
Hong Kong
No. 239 Hong Kong Street
idol Department
------------ now: it is still to obtain the value of the road node under the address node under the node name = "Once unavailable" "," 239 Mars road ",
-------------- C # How to implement it?
OK. At this time, the advantages of LINQ are obvious. The implementation code is as follows:
Private list <string> getxmlresult (string xmlpath, string employeename) {xelement = xelement. load (xmlpath); var query = xelement. descendants ("employee "). singleordefault (x => X. attribute ("name "). value = employeename); If (query! = NULL & query. count ()> 0) {var queryresult = query. descendants ("road "). select (M => M. value); If (queryresult. count ()> 0) return queryresult. tolist <string> ();} return NULL ;}
Without LINQ to XML, using XPath can solve such value problems, but it will become much more complicated.