public static void Main() { //<catalog> // <cd country="USA"> // <title>Empire Burlesque</title> // <artist>Bob Dylan</artist> // <price>10.90</price> // </cd> // <cd country="UK"> // <title>James Bond</title> // <artist>Hello World</artist> // <price>123456</price> // </cd> //</catalog> HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); doc.Load("xml.xml"); var node = doc.DocumentNode.SelectSingleNode("/catalog/cd/@country"); // TODO : 选择的是cd元素而不是country属性 Console.WriteLine(node.GetType()); Console.WriteLine(node); HtmlAgilityPack.HtmlNodeNavigator docx = new HtmlAgilityPack.HtmlNodeNavigator("xml.xml"); var nodex = docx.SelectSingleNode("/catalog/cd/@country"); // TODO 不能使用SelectNodes var ss = nodex.SelectSingleNode("//price"); Debug.WriteLine(ss?.Value ?? "null"); nodex.MoveToRoot(); var ss2 = nodex.SelectSingleNode("//price"); Debug.WriteLine(ss2?.Value ?? "null"); nodex.MoveToFirstChild(); Console.WriteLine(nodex.GetType()); Console.WriteLine(nodex.Value); // 这个解决了属性选择的问题 var r = docx.Select("/catalog/cd/@country").Cast <HtmlNodeNavigator>(); // http://stackoverflow.com/questions/26744559/htmlagilitypack-xpath-and-regex TODO 关于 SelectNodes 的解决方案 var nodes = docx.SelectSet("/catalog/cd/@country"); //XmlDocument doc = new XmlDocument(); //doc.Load("xml.xml"); //var r = doc.DocumentElement.SelectSingleNode("//@country"); // !! XmlDocodument就支持 }
/// <summary> /// 根据 xpath 选择 node, 并将当前 node 转化为 root node /// </summary> /// <remarks>Hesinx 2016-05-26</remarks> /// <param name="navigator"></param> /// <param name="xpath"></param> /// <returns></returns> public static IEnumerable <HtmlNodeNavigator> SelectSetAsRoot(this HtmlNodeNavigator navigator, string xpath) { return(navigator.SelectSet(xpath).Select(m => m.ToRoot())); }