XPathʹÓÃʾÀý£¬Çë¿´ÏÂÃæµÄ´úÂë×¢ÊÍ¡¡
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 StringReader(xml)) { XmlDocument doc = new XmlDocument(); doc.Load(rdr); //È¡ËùÓÐpets½ÚµãϵÄdog×Ö½Úµã XmlNodeList nodeListAllDog = doc.SelectNodes("/pets/dog"); //ËùÓеÄprice½Úµã XmlNodeList allPriceNodes = doc.SelectNodes("//price"); //È¡×îºóÒ»¸öprice½Úµã XmlNode lastPriceNode = doc.SelectSingleNode("//price[last()]"); //ÓÃË«µãºÅÈ¡price½ÚµãµÄ¸¸½Úµã XmlNode lastPriceParentNode = lastPriceNode.SelectSingleNode(".."); //Ñ¡Ôñweight*count=40µÄËùÓж¯ÎʹÓÃͨÅä·û* XmlNodeList nodeList = doc.SelectNodes("/pets/*[@weight*@count=40]"); //Ñ¡Ôñ³ýÁËpigÖ®ÍâµÄËùÓж¯Îï,ʹÓÃname()º¯Êý·µ»Ø½ÚµãÃû×Ö XmlNodeList animalsExceptPigNodes = doc.SelectNodes("/pets/*[name() != 'pig']"); //Ñ¡Ôñ¼Û¸ñ´óÓÚ100¶ø²»ÊÇpigµÄ¶¯Îï XmlNodeList priceGreaterThan100s = doc.SelectNodes("/pets/*[price p @weight >10 and name() != 'pig']"); foreach (XmlNode item in priceGreaterThan100s) { Console.WriteLine(item.OuterXml); } //Ñ¡ÔñµÚ¶þ¸ödog½Úµã XmlNode theSecondDogNode = doc.SelectSingleNode("//dog[position() = 2]"); //ʹÓÃxpath £¬axes µÄ parent È¡¸¸½Úµã XmlNode parentNode = theSecondDogNode.SelectSingleNode("parent::*"); //ʹÓÃxPathÑ¡ÔñµÚ¶þ¸ödog½ÚµãÇ°ÃæµÄËùÓÐdog½Úµã XmlNodeList dogPresibling = theSecondDogNode.SelectNodes("preceding::dog"); //È¡ÎĵµµÄËùÓÐ×ÓËï½Úµãprice XmlNodeList childrenNodes = doc.SelectNodes("descendant::price"); } Console.Read(); } } }ÒÔÉϾÍÊÇxmlѧϰ£¨6£© ÔÚc#XpathʵÀýµÄÄÚÈÝ£¬¸ü¶àÏà¹ØÄÚÈÝÇë¹Ø×¢PHPÖÐÎÄÍø£¨£©£¡
¡¡