.net中使用XPath语言在xml中判断是否存在节点值的方法

book.xml
<?xml version="1.0" encoding="utf-8" ?> <bookstore>
  <book category="COOKING">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>
  <book category="CHILDREN">
    <title lang="en">Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="WEB">
    <title lang="en">XQuery Kick Start</title>
    <author>James McGovern</author>
    <author>Per Bothner</author>
    <author>Kurt Cagle</author>
    <author>James Linn</author>
    <author>Vaidyanathan Nagarajan</author>
    <year>2003</year>
    <price>49.99</price>
  </book>
  <book category="WEB">
    <title lang="en">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>
c#代码:
           //判断是否存在title的取值为:'Harry Potter'的节点存在        
            Stopwatch watch = Stopwatch.StartNew();
            var xmlDoc2 = new XmlDocument();
            xmlDoc2.Load(@"book.xml");      
            var titleTextExpr4 = "/bookstore/book[title='Harry Potter']/title";
            var titleTextNodes4 = xmlDoc2.SelectNodes(titleTextExpr4);               
            Console.WriteLine("XPath表达式为 /bookstore/book[title='Harry Potter']/title,节点数为:" + titleTextNodes4.Count);
            if(titleTextNodes4.Count>0)
            {
                Console.WriteLine("title='Harry Potter'的节点存在");
            }
            else
            {
                Console.WriteLine("title='Harry Potter'的节点不存在");
            }          
            watch.Stop();
            Console.WriteLine("take times(ms)="+watch.ElapsedMilliseconds);

你可能感兴趣的:(xpath)