Return the value for the specific attribute using XPathNodeIterator

I will use the following XML document in the example below.

<?xml version="1.0" encoding="utf-8" ?>
<users>
  <user FirstName="Tom" LastName="Adams" Age="23" />
  <user FirstName="Jhon" LastName="Brams" Age="17" />
  <user FirstName="Bill" LastName="Smith" Age="33" />
</users>

The code prints out all the user nodes of the users node that  have an age with a value greater than 17.

// Read the xml from resource file 
string xml = Resources.Users; 
using (StringReader sr = new StringReader(xml)) 
{ 
    XPathDocument document = new XPathDocument(sr); 
    XPathNavigator navigator = document.CreateNavigator(); 
    XmlNamespaceManager ns = new XmlNamespaceManager(navigator.NameTable); 
    //Selects all the user nodes of the users node that 
    // have an age with a value greater than 17  
    XPathNodeIterator it = navigator.Select("/users/user[@Age>17]"); 
    while (it.MoveNext()) 
    { 
        // access the atributes  
        string firstName = it.Current.GetAttribute("FirstName", ns.DefaultNamespace); 
        string lastName = it.Current.GetAttribute("LastName", ns.DefaultNamespace); 
        // Print out  
        Console.WriteLine( "{0} {1}", firstName, lastName ); 
    } 
}


 
 
 

2 Responses to “Return the value for the specific attribute using XPathNodeIterator”

  1. zproxy
    4. December 2006 at 16:07

    Why not use foreach ?

  2. suresh
    21. August 2010 at 10:59

    this is really good .Helped me at right time
    thx

Leave a Reply