2
var xml= @"<?xml version='1.0'?>
                 <bookstore>
                 <book genre=""3"">
                   <title>The Gorgias3</title>
                   <author>
                     <name>Plato3</name>
                   </author>
                   <price>3</price>
                 </book>
            <book genre=""4"">
                   <title>The Gorgias4</title>
                   <author>
                     <name>Plato4</name>
                   </author>
                   <price>4</price>
                 </book>
            </bookstore>";



XPathDocument docNav = new XPathDocument(new StringReader(xml));
XPathNavigator navigator = docNav.CreateNavigator();
XPathNodeIterator NodeIter = navigator.Select("/bookstore/book/title");

foreach (XPathNavigator selectedNode in NodeIter)
{
    Console.WriteLine(selectedNode.Name);
}

How can i access straight to the first /bookstore/book/title" child and get his value.

I dont want to iterate and break the loop

the result should be "The Gorgias3"

p.s. i dont want to modify the xpath expression with the first filter.

I want to Know how i can do it with c#.

Scott Smith
  • 1,823
  • 17
  • 15
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • Which context are you asking the question in? -- a) knowing the '1st child' is going to be a title -- b) in such a way that you can specify what the first child is (ie title, author, ...) -- I ask because when when I examine your xml my thought without other information would be that the '1st child' is actually and that said child has children as listed above... – Hardryv Feb 01 '12 at 15:30
  • Its an iterator can't it just be casted to node and used? – Usman Ismail Feb 01 '12 at 15:31

1 Answers1

4

Use:

var node = navigator.SelectSingleNode("/bookstore/book/title");

Console.WriteLine(node);
Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125